using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

using C1.Xaml.Chart;
using System.Threading.Tasks;

namespace StockPortfolio
{
    public sealed partial class MyTreasure : UserControl
    {

        public MyTreasure()
        {
            this.InitializeComponent();

            this.Loaded += MyTreasure_Loaded;
            this.Unloaded += MyTreasure_Unloaded;
        }

        void MyTreasure_Unloaded(object sender, RoutedEventArgs e)
        {
            chart.Data.Children.Clear();
            chart.Data.ItemNames = null;
            panelLabel.Visibility = Visibility.Collapsed;
        }

        async void MyTreasure_Loaded(object sender, RoutedEventArgs e)
        {
            await LoadData();
        }

        private async Task LoadData()
        {

            var user = SampleDataSource.GetCurrentUser();
            Balance.Text = " $" + user.Balance.ToString("F2");
            List<double> percent = new List<double>();
            List<string> stocks = new List<string>();
            var stock = await SampleDataSource.GetUserStocksAsync();
            percent.Add(user.Balance);
            stocks.Add("Balance");

            foreach (var item in stock)
            {
                percent.Add(item.CurrentStockQuote.LastTrade * item.Count);
                stocks.Add(item.Symbol);
            }


            var ds = new DataSeries() { ValuesSource = percent };
            ds.PlotElementLoaded += new EventHandler(ds_PlotElementLoaded);

            chart.ManipulationMode = ManipulationModes.All;
            chart.Data.Children.Add(ds);
            chart.ChartType = ChartType.Pie;

            chart.Data.ItemNames = stocks;
            chart.Visibility = Visibility.Visible;
        }

        public double StartingAngle
        {
            get { return (double)GetValue(StartingAngleProperty); }
            set { SetValue(StartingAngleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StartingAngle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StartingAngleProperty =
            DependencyProperty.Register("StartingAngle", typeof(double), typeof(MyTreasure),
            new PropertyMetadata(0.0, new PropertyChangedCallback(OnStartingAngleChanged)));

        static void OnStartingAngleChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
        {
            var uc = (MyTreasure)obj;
            PieOptions.SetStartingAngle(uc.chart, uc.StartingAngle);
        }

        void ds_PlotElementLoaded(object sender, EventArgs e)
        {
            var slice = (PieSlice)sender;
            slice.StrokeThickness = 0;
            slice.ManipulationMode = ManipulationModes.All;
            slice.Tapped += slice_Tapped;

            if (slice.Angle == -90)
            {
                var tt = new TranslateTransform();
                slice.RenderTransform = tt;
                RunAnimation(tt, "Y", TimeSpan.FromSeconds(0.5), -20, new BounceEase());
            }
        }

        void slice_Tapped(object sender, TappedRoutedEventArgs e)
        {
            var slice = (PieSlice)sender;

            if (slice.DataPoint != null)
            {
                txtName.Text = slice.DataPoint.Name;
                int percent=(int)(slice.DataPoint.PercentageSeries * 100);
                txtPopulation.Text = (percent==0?1:percent).ToString() + "%";
            }

            //StartingAngle = StartingAngle - slice.Angle - 90;
            RunAnimation(this, "StartingAngle", TimeSpan.FromSeconds(0.5), StartingAngle - slice.Angle - 90);

            if (panelLabel.Visibility == Windows.UI.Xaml.Visibility.Collapsed)
                panelLabel.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }


        void RunAnimation(DependencyObject target, string targetProperty, TimeSpan time, double to,
          EasingFunctionBase easing = null, System.Action action = null
          )
        {
            var sb = new Storyboard() { Duration = new Duration(time) };
            var da = new DoubleAnimation() { EasingFunction = easing };

            Storyboard.SetTarget(da, target);
            Storyboard.SetTargetProperty(da, targetProperty);

            da.Duration = new Duration(time);
            da.To = to;
            da.EnableDependentAnimation = true;

            sb.Children.Add(da);

            if (action != null)
                sb.Completed += (s, e) => action();

            sb.Begin();
        }
    }
}
