using BellwetherBackend.Utility;
using Microsoft.Win32;
using Microsoft.WindowsAPICodePack.Shell;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace BellwetherBackend.SubPage
{
    /// <summary>
    /// Interaction logic for UcBasicSetting.xaml
    /// </summary>
    public partial class UcFrontPage : UserControl
    {
        private const int avalibleTotalElement = 100;
        private const string frontpageDataPath = @"Data\FrontPage\";

        private Utility.FrontPageJson frontPageJson;
        private int selectMediaIndex = -1;

        public UcFrontPage()
        {
            InitializeComponent();
            //icon load
            AddCategoryToolBar();

            LoadSettingData();

            this.Loaded += UcAbout_Loaded;
        }

        private void UcAbout_Loaded(object sender, RoutedEventArgs e)
        {

            //load media
            List<string> fileLists = frontPageJson.MediaList; //Utility.Setting.AboutComapnyImgList;
            Image imageBuf;
            Grid gridBuf;

            if (fileLists != null)
                for (int fileIndex = 0; fileIndex < fileLists.Count; fileIndex++)
                {
                    Border bd = new Border() { BorderThickness = new Thickness(5), BorderBrush = new SolidColorBrush(Colors.Gray), CornerRadius = new CornerRadius(2), Margin = new Thickness(3, 20, 3, 20), Background = Brushes.White };
                    bd.Focusable = true;
                    bd.PreviewMouseLeftButtonUp += Sc_PreviewMouseLeftButtonUp;
                    string aboutImgDirPath = frontpageDataPath;
                    string path = System.IO.Path.Combine(aboutImgDirPath, fileLists[fileIndex]); //GlobalFunction.rootPath + GlobalFunction.dataFolder + GlobalFunction.multiMediaFolderName + multiMediaJsonData.folderColletion[currentFolderIndex].folderName + @"\" + fileLists[fileIndex];
                    //string path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), fileLists[fileIndex]);

                    if (GlobalFunction.CheckFileIsImage(path))
                    {
                        imageBuf = new Image();
                        //imageBuf.Source = new BitmapImage(new Uri(path));
                        imageBuf.Source = GlobalFunction.GetBitMap(path);
                        imageBuf.Stretch = Stretch.Uniform;
                        gridBuf = new Grid();
                        //imageBuf.TouchDown += StackElemnt_TouchDown;
                        gridBuf.Children.Add(imageBuf);
                        gridBuf.Width = 213;
                        gridBuf.Height = 120;
                        bd.Child = gridBuf;
                        uxFileViewer.Children.Add(bd);
                    }
                    else if (GlobalFunction.CheckFileIsVideo(path))
                    {
                        ShellFile shellFile = ShellFile.FromFilePath(path);
                        imageBuf = new Image();
                        if (shellFile != null && shellFile.Thumbnail != null && shellFile.Thumbnail.ExtraLargeBitmapSource != null)
                            imageBuf.Source = shellFile.Thumbnail.ExtraLargeBitmapSource;
                        //imageBuf.TouchDown += BotImage_TouchDown;
                        imageBuf.Stretch = Stretch.Uniform;
                        gridBuf = new Grid();
                        gridBuf.Width = 213;
                        gridBuf.Height = 120;
                        gridBuf.Children.Add(imageBuf);
                        gridBuf.Children.Add(new Image() { Source = new BitmapImage(new Uri("pack://application:,,,/BellwetherBackend;component/Image/play.png")), Width = 80 });
                        bd.Child = gridBuf;
                        uxFileViewer.Children.Add(bd);
                    }
                }
        }

        private void AddCategoryToolBar()
        {
            new GlobalFunction();
            uxAddBtn.IconData = GlobalFunction.AddBtnData;
            uxDeleteBtn.IconData = GlobalFunction.DeleteBtnData;
            uxUpBtn.IconData = GlobalFunction.MoveUpBtnData;
            uxDownBtn.IconData = GlobalFunction.MoveDownBtnData;
        }

        private void LoadSettingData()
        {
            frontPageJson = Setting.frontPageJsonFile;

            uxSolarEnergyUrlText.Text = frontPageJson.SolarEnergyUrl;

            uxAutoPlaIntervalText.Text = frontPageJson.AutoPlayIntervalSec.ToString();
        }

        private void SaveData()
        {
            Setting.frontPageJsonFile = frontPageJson;
        }

        private void uxSolarUrlText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.IsLoaded)
            {
                uxSolarEnergyUrlText.TextChanged -= uxSolarUrlText_TextChanged;
                frontPageJson.SolarEnergyUrl = uxSolarEnergyUrlText.Text;
                SaveData();
                uxSolarEnergyUrlText.TextChanged += uxSolarUrlText_TextChanged;
            }
        }

        private void uxAutoPlaIntervalText_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (this.IsLoaded)
            {
                uxAutoPlaIntervalText.TextChanged -= uxSolarUrlText_TextChanged;

                if (int.TryParse(uxAutoPlaIntervalText.Text, out var interval))
                {
                    frontPageJson.AutoPlayIntervalSec = interval;
                    SaveData();
                }

                uxAutoPlaIntervalText.TextChanged += uxSolarUrlText_TextChanged;
            }
        }

        private void uxAddBtn_Click(object sender, RoutedEventArgs e)
        {
            if (uxFileViewer.Children.Count >= avalibleTotalElement)
            {
                MessageBox.Show("容許數量已滿");
                return;
            }

            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Multiselect = true;
            openfileDlg.Filter = "Supported files|";
            for (int i = 0; i < GlobalFunction.imgDimList.Count(); i++)
            {
                openfileDlg.Filter += "*" + GlobalFunction.imgDimList[i] + ";";
            }
            for (int i = 0; i < GlobalFunction.mediaDimList.Count(); i++)
            {
                openfileDlg.Filter += "*" + GlobalFunction.mediaDimList[i] + ";";
            }
            //openfileDlg.Filter += "*" + ".PPT" + ";";
            //openfileDlg.Filter += "*" + ".PPTX" + ";";

            if ((bool)openfileDlg.ShowDialog())
            {
                Image imageBuf;
                Grid gridBuf;
                foreach (string name in openfileDlg.FileNames)
                {
                    //string[] imageList = mediaLists[mediaIndex];
                    Border bd = new Border() { BorderThickness = new Thickness(5), BorderBrush = new SolidColorBrush(Colors.Gray), CornerRadius = new CornerRadius(2), Margin = new Thickness(3, 20, 3, 20), Background = Brushes.White };
                    bd.Focusable = true;
                    bd.PreviewMouseLeftButtonUp += Sc_PreviewMouseLeftButtonUp;

                    if (GlobalFunction.CheckFileIsImage(name))
                    {
                        //image
                        string legalFileName = GlobalFunction.GetFolderFileName(frontpageDataPath, name);
                        string fileTo = System.IO.Path.Combine(frontpageDataPath, legalFileName);
                        //複製
                        //File.Copy(name, fileTo);
                        ReduceImageResolution.CheckImageResolution(name, fileTo, 1920, 1080);
                        //json
                        frontPageJson.MediaList.Add(legalFileName);
                        //ux - bd
                        imageBuf = new Image();
                        //imageBuf.Source = new BitmapImage(new Uri(fileTo));
                        imageBuf.Source = GlobalFunction.GetBitMap(fileTo);
                        imageBuf.Stretch = Stretch.Uniform;
                        gridBuf = new Grid();
                        gridBuf.Children.Add(imageBuf);
                        gridBuf.Width = 213;
                        gridBuf.Height = 120;
                        bd.Child = gridBuf;
                        uxFileViewer.Children.Add(bd);
                    }
                    else if (GlobalFunction.CheckFileIsVideo(name))
                    {
                        string legalFileName = GlobalFunction.GetFolderFileName(frontpageDataPath, name);
                        string fileTo = System.IO.Path.Combine(frontpageDataPath, legalFileName);
                        //複製
                        File.Copy(name, fileTo);
                        //json - mediafile
                        frontPageJson.MediaList.Add(legalFileName);
                        //ux - bd
                        ShellFile shellFile = ShellFile.FromFilePath(fileTo);
                        imageBuf = new Image();
                        if (shellFile != null && shellFile.Thumbnail != null && shellFile.Thumbnail.ExtraLargeBitmapSource != null)
                            imageBuf.Source = shellFile.Thumbnail.ExtraLargeBitmapSource;
                        imageBuf.Stretch = Stretch.Uniform;
                        gridBuf = new Grid();
                        gridBuf.Children.Add(imageBuf);
                        gridBuf.Children.Add(new Image() { Source = new BitmapImage(new Uri("pack://application:,,,/BellwetherBackend;component/Image/play.png")), Width = 80 });
                        gridBuf.Width = 213;
                        gridBuf.Height = 120;
                        bd.Child = gridBuf;
                        uxFileViewer.Children.Add(bd);
                    }
                    else if (GlobalFunction.pptDimList.Contains(System.IO.Path.GetExtension(name).ToLower()))
                    {
                        string legalFileName;
                        string fileTo;

                        string tempPath = System.Windows.Forms.Application.StartupPath + @"\Temp";              //暫存資料夾路徑
                        string testResImgFile = tempPath + "\\testResolution.BMP";

                        Microsoft.Office.Interop.PowerPoint.Application pptApplication =
                            new Microsoft.Office.Interop.PowerPoint.Application();
                        Microsoft.Office.Interop.PowerPoint.Presentation pptPresentation =
                        pptApplication.Presentations.Open(name, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue, Microsoft.Office.Core.MsoTriState.msoFalse);
                        //lb_noimage.Refresh();

                        // Export the first page to retrieve its resolution
                        pptPresentation.Slides[1].Export(testResImgFile, "BMP");

                        BitmapImage directImage = new BitmapImage();
                        directImage.BeginInit();
                        directImage.UriSource = new Uri(testResImgFile);
                        directImage.CreateOptions = BitmapCreateOptions.IgnoreColorProfile;
                        directImage.CacheOption = BitmapCacheOption.OnLoad;
                        directImage.EndInit();
                        int width = directImage.PixelWidth;
                        int height = directImage.PixelHeight;

                        // Resolution adaptation
                        if (directImage.PixelWidth > directImage.PixelHeight)
                        {
                            // landscape (1600*900)
                            width = 1600;
                            height = 900;
                        }
                        else
                        {
                            // portrait (900*1600)
                            width = 900;
                            height = 1600;
                        }
                        double bestResFactor = Math.Min((double)width / directImage.PixelWidth, (double)height / directImage.PixelHeight);
                        width = (int)(directImage.PixelWidth * bestResFactor);
                        height = (int)(directImage.PixelHeight * bestResFactor);

                        int slidesCount = pptPresentation.Slides.Count;

                        for (int idx = 1; idx <= slidesCount; idx++)
                        {
                            bd = new Border() { BorderThickness = new Thickness(5), BorderBrush = new SolidColorBrush(Colors.Gray), CornerRadius = new CornerRadius(2), Margin = new Thickness(3, 15, 3, 15) , Background = Brushes.White };
                            bd.PreviewMouseLeftButtonUp += Sc_PreviewMouseLeftButtonUp;

                            legalFileName = GlobalFunction.GetFolderFileName(frontpageDataPath, "1.BMP");
                            fileTo = System.IO.Path.Combine(frontpageDataPath, legalFileName);// GlobalFunction.rootPath + GlobalFunction.dataFolder + GlobalFunction.multiMediaFolderName + multiMediaJsonData.folderColletion[currentFolderIndex].folderName + @"\" + legalFileName;

                            //json - mediafile
                            frontPageJson.MediaList.Add(legalFileName);

                            fileTo = System.IO.Path.Combine(Directory.GetCurrentDirectory(), fileTo);

                            pptPresentation.Slides[idx].Export(fileTo, "BMP", width, height);


                            //ux - bd
                            imageBuf = new Image();
                            //imageBuf.Source = new BitmapImage(new Uri(fileTo));
                            imageBuf.Source = GlobalFunction.GetBitMap(fileTo);
                            imageBuf.Stretch = Stretch.Uniform;
                            gridBuf = new Grid();
                            gridBuf.Children.Add(imageBuf);
                            gridBuf.Width = 213;
                            gridBuf.Height = 120;
                            bd.Child = gridBuf;

                            uxFileViewer.Children.Add(bd);
                        }

                        pptPresentation.Close();

                        System.IO.File.Delete(testResImgFile);
                    }
                }

                if (selectMediaIndex != -1)
                {
                    ((Border)uxFileViewer.Children[selectMediaIndex]).BorderBrush = new SolidColorBrush(Colors.Gray);
                }
                selectMediaIndex = uxFileViewer.Children.Count - 1;
                ((Border)uxFileViewer.Children[selectMediaIndex]).BorderBrush = new SolidColorBrush(Colors.Blue);
                ((Border)uxFileViewer.Children[selectMediaIndex]).Focus();
            }

            Setting.frontPageJsonFile = frontPageJson;
        }

        private void uxDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (selectMediaIndex < 0)
            {
                return;
            }
            uxFileViewer.Children.RemoveAt(selectMediaIndex);
            string path = System.IO.Path.Combine(Directory.GetCurrentDirectory(), frontPageJson.MediaList[selectMediaIndex]);
            File.Delete(System.IO.Path.Combine(frontpageDataPath, frontPageJson.MediaList[selectMediaIndex]));// GlobalFunction.rootPath + GlobalFunction.dataFolder + GlobalFunction.multiMediaFolderName + multiMediaJsonData.folderColletion[currentFolderIndex].folderName + @"\" + multiMediaJsonData.folderColletion[currentFolderIndex].fileNameList[selectMediaIndex]);
            frontPageJson.MediaList.RemoveAt(selectMediaIndex);
            //remove items

            if (frontPageJson.MediaList.Count == 0)
            {
                selectMediaIndex = -1;
            }
            else
            {
                if (selectMediaIndex > (frontPageJson.MediaList.Count - 1))
                {
                    selectMediaIndex = frontPageJson.MediaList.Count - 1;
                }
                else
                {
                    //selectMediaIndex = selectMediaIndex;
                }

                Border gd = uxFileViewer.Children[selectMediaIndex] as Border;
                gd.BorderBrush = new SolidColorBrush(Colors.Blue);
            }

            Setting.frontPageJsonFile = frontPageJson;
        }

        private void uxLeftBtn_Click(object sender, RoutedEventArgs e)
        {
            if (selectMediaIndex > 0)
            {
                Border bdTemp = uxFileViewer.Children[selectMediaIndex] as Border;
                string stTemp = frontPageJson.MediaList[selectMediaIndex];
                uxFileViewer.Children.RemoveAt(selectMediaIndex);
                frontPageJson.MediaList.RemoveAt(selectMediaIndex);
                selectMediaIndex = selectMediaIndex - 1;
                uxFileViewer.Children.Insert(selectMediaIndex, bdTemp);
                frontPageJson.MediaList.Insert(selectMediaIndex, stTemp);
                bdTemp.Focus();

                Setting.frontPageJsonFile = frontPageJson;
            }
        }

        private void uxRightBtn_Click(object sender, RoutedEventArgs e)
        {
            if (selectMediaIndex != (uxFileViewer.Children.Count - 1) && selectMediaIndex >= 0)
            {
                Border bdTemp = uxFileViewer.Children[selectMediaIndex] as Border;
                string stTemp = frontPageJson.MediaList[selectMediaIndex];
                uxFileViewer.Children.RemoveAt(selectMediaIndex);
                frontPageJson.MediaList.RemoveAt(selectMediaIndex);
                selectMediaIndex = selectMediaIndex + 1;
                uxFileViewer.Children.Insert(selectMediaIndex, bdTemp);
                frontPageJson.MediaList.Insert(selectMediaIndex, stTemp);
                bdTemp.Focus();

                Setting.frontPageJsonFile = frontPageJson;
            }
        }

        private void Sc_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            int newIndex = uxFileViewer.Children.IndexOf((Border)sender);
            if (selectMediaIndex == newIndex)
            {
                return;
            }
            else
            {
                Border bd;
                if (selectMediaIndex != -1)
                {
                    bd = uxFileViewer.Children[selectMediaIndex] as Border;
                    bd.BorderBrush = new SolidColorBrush(Colors.Gray);
                }
                selectMediaIndex = newIndex;
                bd = uxFileViewer.Children[selectMediaIndex] as Border;
                bd.BorderBrush = new SolidColorBrush(Colors.Blue);
                bd.Focus();
            }
        }
    }
}
