using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;
using Microsoft.Win32;
using HistoryWallEditTool.JsonFile;
using System.Windows.Threading;

namespace HistoryWallEditTool.ControlsForData
{
    /// <summary>
    /// DetailDataViewer.xaml 的互動邏輯
    /// </summary>
    public partial class DetailDataViewer : UserControl
    {
        private string imgFolderPath = "";
        private int imageCount = -1;
        private int curSelectImgIndex = -1;
        private int defaultContentLength = 300;
        private int curMediaPlay = -1;

        private ListDate listdateData = null;
        private List<string> imgAndmediaList = new List<string>();
        //載入的語系
        private CurrentEditLanguage curLang;

        public DetailDataViewer(int mainIndex, int subIndex, CurrentEditLanguage curLang)
        {
            InitializeComponent();

            listdateData = MainContainer.hweventJson.EventGroups[mainIndex].ListDates[subIndex];
            this.curLang = curLang;
            imgFolderPath = MainContainer.imgFolderName + listdateData.ImagePath;
            //初始化各UI資料
            InitialUiByData();
            //匯入ICON
            AddCategoryToolBar();
        }

        //判斷檔案格式是否為設定的圖片格式
        private bool CheckFileIsImage(string fileExtend)
        {
            if (GlobalFunction.imgDimList.Contains(fileExtend.ToLower()) ||
                GlobalFunction.mediaDimList.Contains(fileExtend.ToLower()))
            {
                return true;
            }
            return false;
        }

        private List<string> GetImageDataList()
        {
            List<string> resultBuf = new List<string>();

            if (Directory.Exists(imgFolderPath))
            {
                string[] files = Directory.GetFiles(imgFolderPath);

                imageCount = files.Count();
                for (int i = 0; i < files.Count(); i++)
                {
                    if (CheckFileIsImage(System.IO.Path.GetExtension(files[i])))
                    {
                        resultBuf.Add(files[i]);
                    }
                }
            }

            return resultBuf;
        }

        private void LoadEventImage()
        {
            imgAndmediaList.Clear();
            //先取得所有圖片及影片的路徑並將路徑放到緩衝區當中
            imgAndmediaList = GetImageDataList();

            //先對檔名重新排列
            imgAndmediaList = ReArrangeImageList();
            uxDetailImgListBox.Items.Clear();
            //載圖開始
            for (int i = 0; i < imgAndmediaList.Count(); i++)
            {
                DetailDataMediaChild ddmc = new DetailDataMediaChild(i);

                if (GlobalFunction.imgDimList.Contains(System.IO.Path.GetExtension(imgAndmediaList[i]).ToLower()))
                {
                    //圖片
                    ddmc.LoadImage(imgAndmediaList[i]);
                }
                else if (GlobalFunction.mediaDimList.Contains(System.IO.Path.GetExtension(imgAndmediaList[i]).ToLower()))
                {
                    //影片~縮圖
                    ddmc.MediaPlayInfoEvent += new DetailDataMediaChild.MediaPlayInfoDelegate(ddmc_MediaPlayInfoEvent);
                    ddmc.LoadMedia(imgAndmediaList[i]);
                }

                uxDetailImgListBox.Items.Add(ddmc);
            }
        }

        public void AutoCloseChildMediaPlay(int curPlayIndex)
        {
            if (curMediaPlay != -1 && curMediaPlay != curPlayIndex)
            {
                DetailDataMediaChild ddmc = uxDetailImgListBox.Items[curMediaPlay] as DetailDataMediaChild;

                ddmc.ExtraOperatorMediaStop();
                ddmc.ReloadMediaThumbImage();
            }
            curMediaPlay = curPlayIndex;
        }

        private void ddmc_MediaPlayInfoEvent(int curPlayIndex)
        {
            AutoCloseChildMediaPlay(curPlayIndex);
        }

        private void CheckContentLength()
        {
            if (uxContent.Text.Length >= defaultContentLength)
            {
                uxOverSign.Opacity = 1;
            }
            else
            {
                uxOverSign.Opacity = 0;
            }
        }

        private void InitialUiByData()
        {
            LoadOtherLanDataByLang(curLang);
            CheckContentLength();

            if (listdateData.ImagePath != "")
            {
                //載入圖片
                LoadEventImage();
            }
        }

        internal void LoadOtherLanDataByLang(CurrentEditLanguage Lang)
        {
            uxEventDate.FlowDirection = HistoryWall.MainBackCollect.LangFlowDir[(int)Lang];
            uxContent.FlowDirection = HistoryWall.MainBackCollect.LangFlowDir[(int)Lang];
            curLang = Lang;
            uxEventDate.Text = listdateData.Month;

            if (curLang == CurrentEditLanguage.LanguageOne)
            {
                uxContent.Text = listdateData.Script1;
            }
            else if (curLang == CurrentEditLanguage.LanguageTwo)
            {
                uxContent.Text = listdateData.Script2;
            }
            else if (curLang == CurrentEditLanguage.LanguageThree)
            {
                uxContent.Text = listdateData.Script3;
            }
            else if (curLang == CurrentEditLanguage.LanguageFour)
            {
                uxContent.Text = listdateData.Script4;
            }
        }

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

        /// <summary>
        /// 複製檔案~ 從 fileFrom 到 imgFolderPath
        /// </summary>
        /// <param name="fileFrom"></param>
        private void CopyFileToTargetFolder(string fileFrom)
        {
            string ExtensionName = System.IO.Path.GetExtension(fileFrom);
            string fileName = String.Format("P{0:D2}", imageCount + 1);
            fileName += ExtensionName;
            string fileTo = "";

            try
            {
                #region 目的圖片資料夾處理
                //如果原本沒有圖片資料夾
                if (listdateData.ImagePath == "")
                {
                    //則重新確認路徑正確 ~ 必須給予一個新的資料夾
                    imgFolderPath = ReCheckImgFolder();
                }
                else
                {
                    //如果有圖片的資料夾~則判斷是否該資料夾存在~不存在則建立
                    if (!Directory.Exists(imgFolderPath))
                    {
                        Directory.CreateDirectory(imgFolderPath);
                    }
                }
                fileTo = imgFolderPath + "\\" + fileName;
                #endregion

                if (GlobalFunction.imgDimList.Contains(ExtensionName.ToLower()))
                {
                    #region 複製圖片處理
                    //重新處理並降低圖片解析度
                    CheckImageResolution(fileFrom, fileTo, GlobalFunction.isSolutionUsing4K);
                    #endregion
                }
                else if (GlobalFunction.mediaDimList.Contains(ExtensionName.ToLower()))
                {
                    #region 複製影片處理
                    CheckMediaResolution(fileFrom, fileTo);
                    #endregion
                }
            }
            catch (Exception)
            {
                MessageBox.Show("已存在" + fileName + "相同檔案名稱");
                return;
            }
        }

        //取得檔案的路徑 + 名稱 並去除副檔名
        private string GetFullPathWithoutExtension(string FilePathName)
        {
            return imgFolderPath + @"\" + System.IO.Path.GetFileNameWithoutExtension(FilePathName);
        }

        //兩個圖片名稱互換
        private void MoveMediaFileListByIndex(int fromIndex, int toIndex)
        {
            string fromFilePathName = imgAndmediaList[fromIndex];
            string toFilePathName = imgAndmediaList[toIndex];
            string bufferFilePathName = imgFolderPath + "\\nLightenBuffer" + System.IO.Path.GetExtension(fromFilePathName);

            //第一個位置先搬到緩衝區當中
            File.Move(fromFilePathName, bufferFilePathName);
            //第二個位置蓋掉第一個位置
            string bufferStr = GetFullPathWithoutExtension(fromFilePathName) + System.IO.Path.GetExtension(toFilePathName);
            File.Move(toFilePathName, bufferStr);
            imgAndmediaList[fromIndex] = bufferStr;
            //緩衝區的資料搬到第二個位置
            bufferStr = GetFullPathWithoutExtension(toFilePathName) + System.IO.Path.GetExtension(fromFilePathName);
            File.Move(bufferFilePathName, bufferStr);
            imgAndmediaList[toIndex] = bufferStr;
        }

        private void MoveDetailImgListByIndex(int fromIndex, int toIndex)
        {
            DetailDataMediaChild ddmcf = uxDetailImgListBox.Items[fromIndex] as DetailDataMediaChild;
            DetailDataMediaChild ddmct = uxDetailImgListBox.Items[toIndex] as DetailDataMediaChild;

            ddmcf.curMediaPath = imgAndmediaList[toIndex];
            ddmcf.curIndex = toIndex;
            ddmct.curMediaPath = imgAndmediaList[fromIndex];
            ddmct.curIndex = fromIndex;

            uxDetailImgListBox.Items.RemoveAt(fromIndex);
            uxDetailImgListBox.Items.Insert(toIndex, ddmcf);

            uxDetailImgListBox.ScrollIntoView(ddmcf);
            uxDetailImgListBox.SelectedIndex = toIndex;
        }

        #region 新增~刪除~上移~下移
        private void uxAddBtn_Click(object sender, RoutedEventArgs e)
        {
            int maxCount = 20 - uxDetailImgListBox.Items.Count;
            OpenFileDialog openfileDlg = new OpenFileDialog();
            openfileDlg.Multiselect = true;
            //過濾檔名
            openfileDlg.Filter = "image 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] + ";";
            }
            //開啟對話框
            if ((bool)openfileDlg.ShowDialog())
            {
                TaskDialogMsg tdm = new TaskDialogMsg();

                tdm.Show();
                for (int i = 0; i < openfileDlg.FileNames.Count(); i++)
                {
                    if (maxCount == 0)
                    {
                        MessageBox.Show((string)FindResource("rejectStr"));
                        break;
                    }

                    CopyFileToTargetFolder(openfileDlg.FileNames[i]);
                    imageCount++;
                    maxCount--;
                }
                //重新載入圖片
                if (openfileDlg.FileNames.Count() > 0)
                {
                    LoadEventImage();
                }
                uxDetailImgListBox.SelectedIndex = uxDetailImgListBox.Items.Count - 1;
                uxDetailImgListBox.ScrollIntoView(uxDetailImgListBox.SelectedItem);
                tdm.DestroyTaskDialogMsg();
            }
        }

        private void waitForCloseMediaTimer_Tick(object sender, EventArgs e)
        {
            DispatcherTimer dt = sender as DispatcherTimer;

            dt.Stop();
            //從資料夾中刪除該圖片~
            File.Delete(imgAndmediaList[curSelectImgIndex]);
            imgAndmediaList.RemoveAt(curSelectImgIndex);
            //移除圖片
            uxDetailImgListBox.Items.RemoveAt(curSelectImgIndex);
            //重新排列檔案名稱
            imgAndmediaList = ReArrangeImageList();
            //資料夾中沒有圖片~則將該資料夾刪除
            if (imgAndmediaList.Count == 0)
            {
                Directory.Delete(imgFolderPath);
                listdateData.ImagePath = "";
            }
            else
            {
                for (int i = 0; i < imgAndmediaList.Count(); i++)
                {
                    //如果是影片~ 因為有播放的問題~ 所以必須重新給予新的名稱
                    if (GlobalFunction.mediaDimList.Contains(System.IO.Path.GetExtension(imgAndmediaList[i]).ToLower()))
                    {
                        DetailDataMediaChild ddmc = uxDetailImgListBox.Items[i] as DetailDataMediaChild;

                        ddmc.curMediaPath = imgAndmediaList[i];
                        ddmc.curIndex = i;
                    }
                }
            }
            imageCount--;
            curSelectImgIndex = -1;
        }

        private void uxDeleteBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curSelectImgIndex != -1)
            {
                // 關閉正在播放的 Media
                AutoCloseChildMediaPlay(-1);
                //delete file 事件緩衝
                DispatcherTimer waitForCloseMediaTimer = new DispatcherTimer();

                waitForCloseMediaTimer.Interval = TimeSpan.FromMilliseconds(150);
                waitForCloseMediaTimer.Tick += new EventHandler(waitForCloseMediaTimer_Tick);
                waitForCloseMediaTimer.Start();
            }
        }

        private void uxUpBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curSelectImgIndex > 0)
            {
                AutoCloseChildMediaPlay(-1);
                //改變圖片的名稱
                MoveMediaFileListByIndex(curSelectImgIndex, curSelectImgIndex - 1);
                //uxDetailImgListBox 圖片位置更換
                MoveDetailImgListByIndex(curSelectImgIndex, curSelectImgIndex - 1);
            }
        }

        private void uxDownBtn_Click(object sender, RoutedEventArgs e)
        {
            if (curSelectImgIndex != -1 && curSelectImgIndex < uxDetailImgListBox.Items.Count - 1)
            {
                AutoCloseChildMediaPlay(-1);
                //改變圖片的名稱
                MoveMediaFileListByIndex(curSelectImgIndex, curSelectImgIndex + 1);
                //uxDetailImgListBox 圖片位置更換
                MoveDetailImgListByIndex(curSelectImgIndex, curSelectImgIndex + 1);
            }
        }
        #endregion

        //重新排列資料夾中的圖片順序 (改檔名)
        private List<string> ReArrangeImageList()
        {
            List<string> resultBuf = new List<string>();

            //先改第一次確認沒有重複
            for (int i = 0; i < imgAndmediaList.Count(); i++)
            {
                string fromFilePathName = imgAndmediaList[i];
                string toFilePathName = imgFolderPath + "\\" + String.Format("HistoryBuf{0:D2}", i) + System.IO.Path.GetExtension(imgAndmediaList[i]);

                File.Move(fromFilePathName, toFilePathName);
                imgAndmediaList[i] = toFilePathName;
            }
            //修改
            for (int i = 0; i < imgAndmediaList.Count(); i++)
            {
                string fromFilePathName = imgAndmediaList[i];
                string toFilePathName = imgFolderPath + "\\" + String.Format("P{0:D2}", i) + System.IO.Path.GetExtension(imgAndmediaList[i]);

                File.Move(fromFilePathName, toFilePathName);
                resultBuf.Add(toFilePathName);
            }

            return resultBuf;
        }

        //重新確認路徑正確否 ~ 如果原本沒有圖片資料夾 ~ 則必須給予一個新的資料夾
        private string ReCheckImgFolder()
        {
            string resultPath = "";
            //給予一個屬於該事件的資料夾
            while (true)
            {
                //使用亂數數字去給與資料夾名稱
                Random Counter = new Random(Guid.NewGuid().GetHashCode());
                int result = Counter.Next(0, 100001);

                resultPath = MainContainer.imgFolderName + result.ToString();
                if (!Directory.Exists(resultPath))
                {
                    Directory.CreateDirectory(resultPath);
                    listdateData.ImagePath = result.ToString();
                    break;
                }
            }

            return resultPath;
        }

        //改變當前焦點圖示
        private void uxDetailImgListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            curSelectImgIndex = uxDetailImgListBox.SelectedIndex;
            //重新設定上下移動的 radiobtn 顯示的狀況
            SetUpDownBtnShow(curSelectImgIndex);
        }

        private void SetUpDownBtnShow(int curItemIndex)
        {
            uxUpBtn.IsEnabled = true;
            uxDownBtn.IsEnabled = true;
            if (curItemIndex <= 0)
            {
                uxUpBtn.IsEnabled = false;
            }

            if (curItemIndex >= uxDetailImgListBox.Items.Count - 1)
            {
                uxDownBtn.IsEnabled = false;
            }
        }

        //失去焦點更新月份資料
        private void uxEventDate_LostFocus(object sender, RoutedEventArgs e)
        {
            listdateData.Month = uxEventDate.Text;
        }

        //失去焦點更新內文資料
        private void uxContent_LostFocus(object sender, RoutedEventArgs e)
        {
            if (curLang == CurrentEditLanguage.LanguageOne)
            {
                listdateData.Script1 = uxContent.Text;
            }
            else if (curLang == CurrentEditLanguage.LanguageTwo)
            {
                listdateData.Script2 = uxContent.Text;
            }
            else if (curLang == CurrentEditLanguage.LanguageThree)
            {
                listdateData.Script3 = uxContent.Text;
            }
            else if (curLang == CurrentEditLanguage.LanguageFour)
            {
                listdateData.Script4 = uxContent.Text;
            }

            CheckContentLength();
        }
    }
}
