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;

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();
        }

        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()
        {
            var solarInfo = GetSolarInfo();

            uxCapacity.Text = solarInfo.Capacity.ToString();

            uxEnergy_Today.Text = solarInfo.Energy_Today.ToString();
            uxCO2EmissionSaved_Today.Text = solarInfo.CO2EmissionSaved_Today.ToString("0.000");
            uxEquivalentTreesPlanted_Today.Text = solarInfo.EquivalentTreesPlanted_Today.ToString("0.000");

            uxEnergy_ThisYear.Text = solarInfo.Energy_ThisYear.ToString();
            uxCO2EmissionSaved_ThisYear.Text = solarInfo.CO2EmissionSaved_ThisYear.ToString("0.000");
            uxEquivalentTreesPlanted_ThisYear.Text = solarInfo.EquivalentTreesPlanted_ThisYear.ToString("0.000");
        }

        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;
        private void HiddeenButton_Click(object sender, MouseButtonEventArgs e)
        {
            if(!(sender is Grid grid))
            {
                return;
            }
            var tag = grid.Tag as string;
            if (string.IsNullOrEmpty(tag))
            {
                hiddenStage = 0;
                return;
            }

            if (hiddenStage == 0)
            {
                if (tag == "0")
                {
                    hiddenStage++;
                }
                else
                {
                    hiddenStage = 0;
                }
            }
            else if (hiddenStage == 1)
            {
                if (tag == "0")
                {
                    hiddenStage++;
                }
                else
                {
                    hiddenStage = 0;
                }
            }
            else if(hiddenStage == 2)
            {
                if (tag == "1")
                {
                    hiddenStage = 0;
                    ExecuteExternal();
                }
                else
                {
                    hiddenStage = 0;
                }
            }
            else
            {
                hiddenStage = 0;
            }
        }

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

    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; }
    }
}
