using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Linq;
using System.Globalization;
using Bellwether.UIComponent;
using System.IO;

namespace Bellwether.Pages
{
    /// <summary>
    /// Interaction logic for ucFrontPage.xaml
    /// </summary>
    public partial class ucFrontPage : UserControl
    {

        public ucFrontPage()
        {
            InitializeComponent();

            //var sbTimerPanelEffect = FindResource("sbSolarLight") as Storyboard;
            //var sbDatetimePanelEffectt = FindResource("sbDatetimeLight") as Storyboard;
            //sbTimerPanelEffect.Begin();
            //sbDatetimePanelEffectt.Begin();

            SolarInfpoUpdateTimer = new Timer() { Interval = 300_000 };
            DateTimeUpdateTimer = new Timer() { Interval = 60_000 };

            Loaded += UcFrontPage_Load;
            Unloaded += UcFrontPage_Unload;
        }

        public event EventHandler<PageType> GoPageRequested;

        private Timer SolarInfpoUpdateTimer;
        private Timer DateTimeUpdateTimer;

        private void UcFrontPage_Load(object sender, EventArgs e)
        {
            SolarInfpoUpdateTimer.Elapsed += SolarInfpoUpdateTimer_Elapsed;
            DateTimeUpdateTimer.Elapsed += DateTimeUpdateTimer_Elapsed;

            List<string> imgPathList = Utility.Setting.MediaList;
            for (int imgIndex = 0; imgIndex < imgPathList.Count; imgIndex++)
            {
                imgPathList[imgIndex] = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(),"Data","FrontPage", imgPathList[imgIndex]);
            }
            uxMediaViewer.MediaPathList = imgPathList;

            UpdateSolarInfo();
            UpdateDateTimeInfo();
            SolarInfpoUpdateTimer.Start();
            DateTimeUpdateTimer.Start();

            LoadSolarInfoBg();
        }

        private void LoadSolarInfoBg()
        {
            var bgFilePath = Properties.Settings.Default.SolarPanelBg;
            if (!File.Exists(bgFilePath))
            {
                return;
            }
            bgFilePath = System.IO.Path.GetFullPath(bgFilePath);
            uxBg.Source = Utility.GlobalFunction.GetBitMap(bgFilePath, 1920, 1080);
        }

        private void UcFrontPage_Unload(object sender, EventArgs e)
        {
            SolarInfpoUpdateTimer.Elapsed -= SolarInfpoUpdateTimer_Elapsed;
            SolarInfpoUpdateTimer.Stop();
        }

        private void SolarInfpoUpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.Invoke(() => {
                UpdateSolarInfo();
            });
        }

        private void DateTimeUpdateTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Dispatcher.Invoke(() => {
                UpdateDateTimeInfo();
            });
        }

        private void UpdateSolarInfo()
        {
            UpdateTitlePanel();
            UpdateSolarEnergyPanel();
            UpdateSolarCapacityPanel();
        }

        private async Task UpdateSolarCapacityPanel()
        {
            var energyCapacity = await BellwetherAPI.GetSolarenergyCapacity();

            uxSolarCapacityPanel.Children.Clear();
            uxSolarCapacityPanel.ColumnDefinitions.Clear();

            var total = energyCapacity.Count;
            if (total <= 0)
                return;

            if (total == 1)
            {
                AddSingalSolarCapacity(energyCapacity[0]);
                return;
            }

            if (total == 2)
            {
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

                var firstElemnt = CreateEnergyCapacityInfoPanel(energyCapacity[0]);
                Grid.SetColumn(firstElemnt, 1);
                uxSolarCapacityPanel.Children.Add(firstElemnt);

                var secondElemnt = CreateEnergyCapacityInfoPanel(energyCapacity[1]);
                Grid.SetColumn(secondElemnt, 3);
                uxSolarCapacityPanel.Children.Add(secondElemnt);

                return;
            }


            uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            for (int colIndex = 1; colIndex < total; colIndex++)
            {
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
                uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            }

            for (int dataIndex = 0; dataIndex < total; dataIndex++)
            {
                var panel = CreateEnergyCapacityInfoPanel(energyCapacity[dataIndex]);
                Grid.SetColumn(panel, dataIndex * 2);
                uxSolarCapacityPanel.Children.Add(panel);
            }
        }

        private void AddSingalSolarCapacity(Model.SolarenergyCapacityModel solarenergyCapacityModel)
        {
            uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });
            uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            uxSolarCapacityPanel.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

            var infoPanel = CreateEnergyCapacityInfoPanel(solarenergyCapacityModel);
            Grid.SetColumn(infoPanel, 1);
            uxSolarCapacityPanel.Children.Add(infoPanel);
        }

        private async Task UpdateSolarEnergyPanel()
        {
            var solarEnergyInfo = await BellwetherAPI.GetSolarenergy();
            var primary = solarEnergyInfo.Take(2).ToList();
            var secondary = solarEnergyInfo.Skip(2).ToList();
            UpdateSolarEnergyPrimaryPanel(primary);
            UpdateSolarEnergySecondaryPanel(secondary);
        }

        private void UpdateSolarEnergyPrimaryPanel(List<Model.SolarEnergyModel> primary)
        {
            if (primary.Count > 0)
            {
                var p1 = primary[0];
                uxPrimarySolarInfo00.Text = p1.Area;
                uxPrimarySolarInfo01.Text = p1.Unit;
                uxPrimarySolarInfo02.Text = p1.Energy;
                uxPrimarySolarInfo03.Text = p1.CO2EmissionSaved;
                uxPrimarySolarInfo04.Text = p1.EquivalentTreesPlanted;
            }
            else
            {
                uxPrimarySolarInfo00.Text = "";
                uxPrimarySolarInfo01.Text = "";
                uxPrimarySolarInfo02.Text = "";
                uxPrimarySolarInfo03.Text = "";
                uxPrimarySolarInfo04.Text = "";
            }

            if (primary.Count > 1)
            {
                var p2 = primary[1];
                uxPrimarySolarInfo10.Text = p2.Area;
                uxPrimarySolarInfo11.Text = p2.Unit;
                uxPrimarySolarInfo12.Text = p2.Energy;
                uxPrimarySolarInfo13.Text = p2.CO2EmissionSaved;
                uxPrimarySolarInfo14.Text = p2.EquivalentTreesPlanted;
            }
            else
            {
                uxPrimarySolarInfo10.Text = "";
                uxPrimarySolarInfo11.Text = "";
                uxPrimarySolarInfo12.Text = "";
                uxPrimarySolarInfo13.Text = "";
                uxPrimarySolarInfo14.Text = "";
            }
        }

        private void UpdateSolarEnergySecondaryPanel(List<Model.SolarEnergyModel> secondaryDatas)
        {
            const int MAX_ROW = 5;
            uxSolarSecondaryForm.Children.Clear();
            for (int dataIndex = 0; dataIndex < secondaryDatas.Count && dataIndex < MAX_ROW; dataIndex++)
            {
                var data = secondaryDatas[dataIndex];

                var area = CreateSolarEnergySecondaryInfo(data.Area, isTitle: true);
                Grid.SetColumn(area, 0);
                Grid.SetRow(area, dataIndex);
                uxSolarSecondaryForm.Children.Add(area);

                var unit = CreateSolarEnergySecondaryInfo(data.Unit, isTitle: true);
                Grid.SetColumn(unit, 1);
                Grid.SetRow(unit, dataIndex);
                uxSolarSecondaryForm.Children.Add(unit);

                var energy = CreateSolarEnergySecondaryInfo(data.Energy);
                Grid.SetColumn(energy, 2);
                Grid.SetRow(energy, dataIndex);
                uxSolarSecondaryForm.Children.Add(energy);

                var co2 = CreateSolarEnergySecondaryInfo(data.CO2EmissionSaved);
                Grid.SetColumn(co2, 3);
                Grid.SetRow(co2, dataIndex);
                uxSolarSecondaryForm.Children.Add(co2);

                var trees = CreateSolarEnergySecondaryInfo(data.EquivalentTreesPlanted);
                Grid.SetColumn(trees, 4);
                Grid.SetRow(trees, dataIndex);
                uxSolarSecondaryForm.Children.Add(trees);
            }
        }

        private async Task UpdateTitlePanel()
        {
            var titleInfo1 = await BellwetherAPI.GetSolarenergyTitle1();
            if (!string.IsNullOrEmpty(titleInfo1.Title))
            {
                uxTitleText1.Text = titleInfo1.Title;
                uxTitleNNum1.Text = titleInfo1.Content.ToString();
            }
            else
            {
                uxTitleText1.Text = "";
                uxTitleNNum1.Text = "";
            }
            var titleInfo2 = await BellwetherAPI.GetSolarenergyTitle2();
            if (!string.IsNullOrEmpty(titleInfo2.Title))
            {
                uxTitleText2.Text = titleInfo2.Title;
                uxTitleNNum2.Text = titleInfo2.Content.ToString();
            }
            else
            {
                uxTitleText2.Text = "";
                uxTitleNNum2.Text = "";
            }
        }

        private void UpdateDateTimeInfo()
        {
            var dateTimeNow = DateTime.Now;
            var dateString = dateTimeNow.ToString("yyyy/MM/dd");
            var timeString = dateTimeNow.ToString("HH:mm");
            var weekString = dateTimeNow.ToString("dddd");

            uxDate.Text = dateString;
            uxTime.Text = timeString;
            uxWeek.Text = weekString;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            GoPageRequested?.Invoke(this, PageType.History);
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            GoPageRequested?.Invoke(this, PageType.Product);
        }

        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            GoPageRequested?.Invoke(this, PageType.CSR);
        }

        private SolarInfoModel GetSolarInfo()
        {
            var url = Utility.Setting.SolarEnergyUrl;
            if (string.IsNullOrEmpty(url))
            {
                url = "https://dsegomspoctestenv.azurewebsites.net/api/siteoverview?act=9237&token=BWsolarenergy";
            }
            var client = new RestSharp.RestClient(url);
            var request = new RestSharp.RestRequest(RestSharp.Method.GET);
            //request.AddParameter("act", "9237");
            //request.AddParameter("token", "BWsolarenergy");

            var response = client.Execute(request);

            if (response.IsSuccessful)
            {
                var result = response.Content;

                if (result.StartsWith("\""))
                {
                    result = result.Substring(1);
                }
                if (result.EndsWith("\""))
                {
                    result = result.Substring(0, result.Length - 1);
                }
                result = result.Replace("\\\"", "\"");

                try
                {
                    var data = JsonConvert.DeserializeObject<SolarInfoModel>(result);

                    if (data != null)
                    {
                        return data;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace);
                    Console.WriteLine(e.Message);
                    return null;
                }
            }
            else
            {
                var errmsg = response.Content;
                Console.WriteLine(errmsg);
            }
            return null;
        }

        int hiddenStage = 0;
        Timer hiddenStageTimer;
        private void HiddenButton_TouchDown(object sender, RoutedEventArgs e)
        {
            TryInitTimer();
            //var touchPoints = e.GetIntermediateTouchPoints(this);

            hiddenStage++;
            if (hiddenStage == 1)
            {
                hiddenStageTimer.Start();
            }
            if (hiddenStage == 2)
            {
                hiddenStageTimer.Stop();
                hiddenStage = 0;
                //ExecuteExternal();
                ChangeToScreenSavePage();
            }

            void TryInitTimer()
            {
                if (hiddenStageTimer != null)
                {
                    return;
                }

                hiddenStageTimer = new Timer() { Interval = 1000 };
                hiddenStageTimer.Elapsed += (sender2, e2) => {
                    hiddenStage = 0;
                    hiddenStageTimer.Stop();
                };
            }

            async void ExecuteExternal()
            {
                uxMediaViewer.Stop();
                await Task.Delay(100);
                try
                {
                    var p = Process.Start(Properties.Settings.Default.Screensaver);
                    p.WaitForExit();
                }
                catch (Exception e2)
                {
                    MessageBox.Show("螢幕保護程式啟動失敗，請確認程式存在且路徑非C:\\Windows\\System32");
                }
                uxMediaViewer.Play();
            }

            async void ChangeToScreenSavePage()
            {
                GoPageRequested?.Invoke(this, PageType.ScreenSave);
            }
        }

        int hiddenStage2 = 0;
        Timer hiddenStage2Timer;
        private void HiddenButton2_TouchDown(object sender, RoutedEventArgs e)
        {
            TryInitTimer();

            hiddenStage2++;
            if (hiddenStage2 == 1)
            {
                hiddenStage2Timer.Start();
            }
            if (hiddenStage2 == 2)
            {
                hiddenStage2Timer.Stop();
                hiddenStage2 = 0;
                Application.Current.Shutdown();
            }

            void TryInitTimer()
            {
                if (hiddenStage2Timer != null)
                {
                    return;
                }

                hiddenStage2Timer = new Timer() { Interval = 100 };
                hiddenStage2Timer.Elapsed += (sender2, e2) => {
                    hiddenStage2 = 0;
                    hiddenStage2Timer.Stop();
                };
            }
        }

        private UIElement CreateSolarEnergySecondaryInfo(string data, bool isTitle = false)
        {
            var dataString = data;
            dataString = string.IsNullOrEmpty(dataString) ? " " : dataString;
            return new SpacedLabel()
            {
                Text = dataString,
                FontSize = 43,
                Margin = new Thickness(0, -10, 0, 0),
                FontWeight = isTitle ? FontWeights.Bold : FontWeights.Normal,
                FontColor = Colors.White,
                HorizontalAlignment = isTitle ? HorizontalAlignment.Center : HorizontalAlignment.Right,
                FontFamily = new FontFamily("Microsoft JhengHei"),
                Spaceing = -10
            };
        }

        private UIElement CreateEnergyCapacityInfoPanel(Model.SolarenergyCapacityModel solarenergyCapacityModel)
        {
            Grid rootGrid = new Grid();
            rootGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
            rootGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = new GridLength(30, GridUnitType.Pixel) });
            rootGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });

            var area = solarenergyCapacityModel.Area;
            area = string.IsNullOrEmpty(area) ? " " : area;
            var title = new SpacedLabel()
            {
                Text = area,
                FontSize = 35,
                Margin = new Thickness(-10, 0, 0, 0),
                FontWeight = FontWeights.Bold,
                FontColor = Color.FromRgb(37, 66, 152),
                FontFamily = new FontFamily("Microsoft JhengHei"),
                Spaceing = -10
            };
            Grid.SetColumn(title, 0);
            rootGrid.Children.Add(title);

            var arror = new SpacedLabel()
            {
                Text = "▸",
                Margin = new Thickness(-5, 0, 0, 0),
                FontSize = 35,
                FontColor = Color.FromRgb(0, 104, 232),
                FontFamily = new FontFamily("Microsoft JhengHei"),
                Spaceing = -10
            };
            Grid.SetColumn(arror, 1);
            rootGrid.Children.Add(arror);

            var capacity = solarenergyCapacityModel.Capacity;
            capacity = string.IsNullOrEmpty(capacity) ? " " : capacity;
            var capacityLabel = new SpacedLabel()
            {
                Margin = new Thickness(-7, 0, 0, 0),
                Text = capacity,
                FontSize = 35,
                FontColor = Color.FromRgb(0, 104, 232),
                FontFamily = new FontFamily("Microsoft JhengHei"),
                Spaceing = -10
            };
            Grid.SetColumn(capacityLabel, 2);
            rootGrid.Children.Add(capacityLabel);

            return rootGrid;
        }
    }

    public class SolarInfoModel
    {
        public float Capacity { get; set; }
        public double Energy_Today { get; set; }
        public double CO2EmissionSaved_Today { get; set; }
        public double EquivalentTreesPlanted_Today { get; set; }
        public double Energy_ThisYear { get; set; }
        public double CO2EmissionSaved_ThisYear { get; set; }
        public double EquivalentTreesPlanted_ThisYear { get; set; }
    }
}
