using System;
using System.Collections.Generic;

using C1.Silverlight.DataGrid;


namespace C1DataGrid_Demo2010
{
    /// <summary>
    /// Handles custom merging, like Excel
    /// </summary>
    public class MergerAdHoc
    {
        #region Merge

        public virtual bool CanMergeRange(DataGridCellsRange newRange)
        {
            if (newRange.IsSingleCell())
                return false;

            foreach (var range in _mergedRanges)
            {
                if (newRange.Intersects(range))
                {
                    return false;
                }
            }
            return true;
        }

        public void MergeRange(DataGridCellsRange newRange) 
        {
            if (!CanMergeRange(newRange))
                throw new InvalidOperationException("Can't add this range to the collection");

            _mergedRanges.Add(newRange);
        }

        #endregion

        #region Unmerge

        public bool CanUnmergeRange(DataGridCellsRange range)
        {
            if (_mergedRanges.Count == 0)
                return false;

            return (RangesToRemove(range).Count > 0);
        }

        public bool UnmergeRange(DataGridCellsRange range)
        {
            var list = RangesToRemove(range);

            bool res = false;
            foreach (var r in list)
            {
                _mergedRanges.Remove(r);
                res = true;
            }
            return res;
        }

        private List<DataGridCellsRange> RangesToRemove(DataGridCellsRange range)
        {
            var tmp = new List<DataGridCellsRange>();
            foreach (var r in _mergedRanges)
            {
                if (range.Contains(r) || (range.IsSingleCell() && r.TopLeftCell == range.TopLeftCell))
                {
                    tmp.Add(r);
                }
            }
            return tmp;
        }

        #endregion

        protected List<DataGridCellsRange> _mergedRanges = new List<DataGridCellsRange>();
        public IEnumerable<DataGridCellsRange> MergedRanges
        {
            get
            {
                return _mergedRanges;
            }
        }
    }
}
