using C1.Xaml.Chart;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Navigation;

namespace DrillDown
{
    public sealed partial class SunburstSample : Page
    {
        private DrillDownViewModel _vm;
        public SunburstSample()
        {
            this.InitializeComponent();
            this.Unloaded += SunburstSample_Unloaded;
            _vm = new DrillDownViewModel();
            this.DataContext = _vm;
        }

        private void SunburstSample_Unloaded(object sender, RoutedEventArgs e)
        {
            if (adorner != null)
            {
                var popUp = adorner.Adorner;
                if (popUp.IsOpen)
                {
                    popUp.IsOpen = false;
                }
            }
        }

        private void Chart_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var flexChart = sender as FlexChartBase;
            
            var hitInfo = flexChart.HitTest(e.GetPosition(flexChart));
            if (hitInfo != null && hitInfo.Distance < 2)
            {
                _vm.DataLayer.DrillDown(hitInfo.PointIndex);
            }
        }

        SunburstAdorner adorner;
        private void HandleSunburstRendering(object sender, RenderEventArgs e)
        {
            if (adorner == null)
                adorner = new SunburstAdorner(sunburst);
        }

        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            base.OnNavigatingFrom(e);
            if (adorner != null)
            {
                adorner = null;
            }
        }

    }
}
