using System.ComponentModel;
using C1.Silverlight.FlexGrid;

namespace C1.Silverlight.FlexGridExcel
{
    /// <summary>
    /// Undoable sort action for bound grids.
    /// </summary>
    public class SortAction : IUndoableAction
    {
        //-------------------------------------------------------------------------
        #region ** fields

        C1FlexGrid _flex;
        SortDescription[] _oldSortDescriptions;
        SortDescription[] _newSortDescriptions;

        #endregion

        //-------------------------------------------------------------------------
        #region ** ctor

        /// <summary>
        /// Initializes a new instance of an <see cref="SortAction"/>.
        /// </summary>
        /// <param name="sender"><see cref="C1FlexGrid"/> that owns the action.</param>
        /// <param name="oldSortDescriptions">Array that contains the sort descriptions values before the action.</param>
        public SortAction(object sender, SortDescription[] oldSortDescriptions)
        {
            _flex = sender as C1FlexGrid;
            _oldSortDescriptions = oldSortDescriptions;
            if (_flex.CollectionView != null)
            {
                _newSortDescriptions = new SortDescription[_flex.CollectionView.SortDescriptions.Count];
                _flex.CollectionView.SortDescriptions.CopyTo(_newSortDescriptions, 0);
            }
        }

        #endregion

        //-------------------------------------------------------------------------
        #region ** IUndoableAction

        /// <summary>
        /// Reverts the effect of the last action.
        /// </summary>
        public void Undo()
        {
            SetSortDescriptions(_oldSortDescriptions);
        }
        /// <summary>
        /// Restores the effect of the last undone action.
        /// </summary>
        public void Redo()
        {
            SetSortDescriptions(_newSortDescriptions);
        }

        #endregion

        //-------------------------------------------------------------------------
        #region ** implementation

        void SetSortDescriptions(SortDescription[] sortDescriptions)
        {
            if (_flex.CollectionView != null && _flex.CollectionView.CanSort)
            {
                using (_flex.CollectionView.DeferRefresh())
                {
                    _flex.CollectionView.SortDescriptions.Clear();
                    for (int i = 0; i < sortDescriptions.Length; i++)
                    {
                        _flex.CollectionView.SortDescriptions.Add(sortDescriptions[i]);
                    }
                }
            }
        }

        #endregion
    }
}