using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Telerik.Windows.Controls.GridView;
using Telerik.Windows.Controls.DragDrop;
using Telerik.Windows.Controls;
using System.Diagnostics;
using System.Collections.ObjectModel;

namespace SL.DragColumns
{
    public partial class MainPage : UserControl
    {
        private GridViewGroupPanel groupPanel;

        private GridViewGroupPanel GroupPanel
        {
            get
            {
                if (groupPanel == null)
                {
                    groupPanel = this.SampleGrid.ChildrenOfType<GridViewGroupPanel>().FirstOrDefault();
                }
                return groupPanel;
            }
        }

        public MainPage()
        {
            InitializeComponent();

            this.DataContext = (from c in Enumerable.Range(0, 10) select new SampleData { ID = c, Name = "Name" + c }).ToList();
            this.SampleGrid.LayoutUpdated += new EventHandler(SampleGrid_LayoutUpdated);
        }

        void SampleGrid_LayoutUpdated(object sender, EventArgs e)
        {
            AttachToHeaderCells();
        }


        private void AttachToHeaderCells()
        {
            var cells = this.ChildrenOfType<GridViewHeaderCell>();
            if (cells.Count > 1)
            {
                foreach (var cell in cells)
                {
                    RadDragAndDropManager.RemoveDragInfoHandler(cell, OnDragInfo);
                    RadDragAndDropManager.AddDragInfoHandler(cell, OnDragInfo);
                }


                this.SampleGrid.LayoutUpdated -= SampleGrid_LayoutUpdated;
            }
        }


        private void OnDragInfo(object sender, DragDropEventArgs args)
        {
            var cell = args.Options.Source as GridViewHeaderCell;
            if (cell!=null && cell.Column!=null && (args.Options.Status == DragStatus.DragCancel || args.Options.Status == DragStatus.DropCancel))
            {

                cell.Column.IsVisible = false;
            }
        }
    }

    public class SampleData
    {

        public int ID { get; set; }
        public string Name { get; set; }
        public bool Active { get; set; }
    }
}
