using C1.Xaml.Chart;
using System;
using Windows.Foundation;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

namespace ControlExplorer.Controls.Chart
{
    public partial class DependentAxes
        : UserControl
    {
        public DependentAxes()
        {
            InitializeComponent();

            Loaded += DependentAxes_Loaded;
        }

        void DependentAxes_Loaded(object sender, RoutedEventArgs e)
        {
            chart.Data.Children.Add(CreateTestData(DateTime.Today, 100));
            chart.Actions.Add(new ScaleAction()); // double-tap
            chart.Actions.Add(new TranslateAction()); // drag
            chart.View.AxisX.IsTime = true;
            chart.View.AxisX.Scale = 0.2;
            CreateTitle(chart.View.AxisY, "°C", null);

            Axis axf = new Axis()
            {
                AxisType = AxisType.Y,
                IsDependent = true,
                Foreground = new SolidColorBrush(Color.FromArgb(255, 139, 0, 0)),
                DependentAxisConverter = (x) => x * 9 / 5 + 32
            };
            CreateTitle(axf, "°F", new SolidColorBrush(Color.FromArgb(255, 139, 0, 0)));
            chart.View.Axes.Add(axf);

            Axis axk = new Axis()
            {
                IsDependent = true,
                Foreground = new SolidColorBrush(Color.FromArgb(255, 21, 118, 118)),
                DependentAxisConverter = (x) => x + 273.15,
                Position = AxisPosition.Far
            };
            CreateTitle(axk, "K", new SolidColorBrush(Color.FromArgb(255, 21, 118, 118)));
            chart.View.Axes.Add(axk);
        }

        Random rnd = new Random();

        XYDataSeries CreateTestData(DateTime start, int cnt)
        {
            DateTime[] x = new DateTime[cnt];
            double[] y = new double[cnt];

            for (int i = 0; i < cnt; i++)
            {
                x[i] = start.AddDays(i);
                y[i] = -10 + 20 * rnd.NextDouble();
            }

            return new XYDataSeries() { XValuesSource = x, ValuesSource = y };
        }

        void CreateTitle(Axis ax, string text, SolidColorBrush fg)
        {
            TextBlock tb = new TextBlock()
            {
                TextAlignment = TextAlignment.Right,
                Text = text,
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Bottom,
                Width = 20,
                RenderTransform = new RotateTransform() { Angle = 90 },
                RenderTransformOrigin = new Point(0.5, 0.5) // new Point(0.8,1.1),
            };

            if (fg != null)
                tb.Foreground = fg;

            ax.Title = new Border()
            {
                HorizontalAlignment = HorizontalAlignment.Left,
                VerticalAlignment = VerticalAlignment.Top,
                Child = tb,
            };
        }
    }
}