using ComPDFKit.PDFDocument;
using ComPDFKit.PDFPage;
using ComPDFKit.PDFPage.Edit;
using ComPDFKit.Tool;
using ComPDFKit.Tool.UndoManger;
using ComPDFKitViewer;
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Media;

namespace Compdfkit_Tools.Edit
{
    public partial class PDFImageEditControl : UserControl
    {
        public CPDFViewerTool ToolView { get; set; }
        public ImageEditParam EditEvent { get; set; }

        public PDFImageEditControl()
        {
            InitializeComponent();
            Loaded += PDFImageEditControl_Loaded;
            Unloaded += PDFImageEditControl_Unloaded;
        }

        private void PDFImageEditControl_Unloaded(object sender, RoutedEventArgs e)
        {
            RotateUI.RotationChanged -= RotateUI_RotationChanged;
            FlipUI.FlipChanged -= FlipUI_FlipChanged;
        }

        public void InitWithPDFViewer(CPDFViewerTool newPDFView)
        {
            ToolView = newPDFView;
        }

        public void SetPDFImageEditData(ImageEditParam newEvent)
        {
            EditEvent = null;
            if (newEvent != null && newEvent.EditType == CPDFEditType.EditImage)
            {
                SetImageTransparency(newEvent.Transparency);
            }
            EditEvent = newEvent;
            SetImageThumb();
        }

        private void PDFImageEditControl_Loaded(object sender, RoutedEventArgs e)
        {
            RotateUI.RotationChanged += RotateUI_RotationChanged;
            FlipUI.FlipChanged += FlipUI_FlipChanged;
        }

        private void FlipUI_FlipChanged(object sender, bool e)
        {
            GetImageArea(out CPDFEditImageArea imageArea, out CPDFPage pdfPage, out CPDFEditPage editPage);
            if (imageArea != null)
            {
                bool result = false;
                if (e)
                {
                    result = imageArea.VerticalMirror();
                }
                else
                {
                    result = imageArea.HorizontalMirror();
                }
                if (result)
                {
                    PDFEditHistory editHistory = new PDFEditHistory();
                    editHistory.EditPage = editPage;
                    if (pdfPage != null)
                    {
                        editHistory.PageIndex = pdfPage.PageIndex;
                    }

                    ToolView.GetCPDFViewer()?.UndoManager.AddHistory(editHistory);
                }

                SetImageThumb();
            }
        }

        private void RotateUI_RotationChanged(object sender, double e)
        {
            GetImageArea(out CPDFEditImageArea imageArea, out CPDFPage pdfPage, out CPDFEditPage editPage);
            if (imageArea != null)
            {
                if (imageArea.Rotate((float)e))
                {
                    PDFEditHistory editHistory = new PDFEditHistory();
                    editHistory.EditPage = editPage;
                    if (pdfPage != null)
                    {
                        editHistory.PageIndex = pdfPage.PageIndex;
                    }

                    ToolView.GetCPDFViewer()?.UndoManager.AddHistory(editHistory);
                    SetImageThumb();
                }
            }
        }

        private void Slider_DragStarted(object sender, DragStartedEventArgs e)
        {
            Slider slider = sender as Slider;
            if (slider != null)
            {
                slider.Tag = "false";
            }
        }

        private void SliderOpacity_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            Slider slider = sender as Slider;
            if (slider != null)
            {
                slider.Tag = "true";
            }
            GetImageArea(out CPDFEditImageArea imageArea, out CPDFPage pdfPage, out CPDFEditPage editPage);
            if (imageArea != null)
            {
                if (imageArea.SetImageTransparency((byte)(ImasgeOpacitySlider.Value * 255)))
                {
                    PDFEditHistory editHistory = new PDFEditHistory();
                    editHistory.EditPage = editPage;
                    if (pdfPage != null)
                    {
                        editHistory.PageIndex = pdfPage.PageIndex;
                    }

                    ToolView.GetCPDFViewer()?.UndoManager.AddHistory(editHistory);
                    SetImageThumb();
                }
            }
        }

        private void SliderOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            Slider slider = sender as Slider;
            if(OpacityTextBox != null)
            {
                OpacityTextBox.Text = string.Format("{0}%", (int)(ImasgeOpacitySlider.Value * 100));
            }
          
            if (slider != null && slider.Tag != null && slider.Tag.ToString() == "false")
            {
                return;
            }
            GetImageArea(out CPDFEditImageArea imageArea, out CPDFPage pdfPage, out CPDFEditPage editPage);
            if (imageArea != null)
            {
                if (imageArea.SetImageTransparency((byte)(ImasgeOpacitySlider.Value * 255)))
                {
                    PDFEditHistory editHistory = new PDFEditHistory();
                    editHistory.EditPage = editPage;
                    if (pdfPage != null)
                    {
                        editHistory.PageIndex = pdfPage.PageIndex;
                    }

                    ToolView.GetCPDFViewer()?.UndoManager.AddHistory(editHistory);
                    SetImageThumb();
                }
            }
        }

        private void ImageReplaceBtn_Click(object sender, RoutedEventArgs e)
        {
            if (EditEvent != null)
            {
                OpenFileDialog openFileDialog = new OpenFileDialog();
                openFileDialog.Filter = "Image Files(*.jpg;*.jpeg;*.png;*.bmp)|*.jpg;*.jpeg;*.png;*.bmp;";
                if (openFileDialog.ShowDialog() == true)
                {
                    GetImageArea(out CPDFEditImageArea imageArea, out CPDFPage pdfPage, out CPDFEditPage editPage);
                    if (imageArea != null)
                    {
                        Rect imageRect= imageArea.GetClipRect();
                        if (imageArea.ReplaceImageArea(imageRect,openFileDialog.FileName,string.Empty))
                        {
                            PDFEditHistory editHistory = new PDFEditHistory();
                            editHistory.EditPage = editPage;
                            if (pdfPage != null)
                            {
                                editHistory.PageIndex = pdfPage.PageIndex;
                            }

                            ToolView.GetCPDFViewer()?.UndoManager.AddHistory(editHistory);
                            SetImageThumb();
                        }
                    }
                }
            }
        }

        private void ImageExportBtn_Click(object sender, RoutedEventArgs e)
        {
            if (ToolView != null)
            {
                //需要选中图片对象
                // Dictionary<int, List<Bitmap>> imageDict = PDFView.GetSelectedImages();
                Dictionary<int, List<Bitmap>> imageDict=new Dictionary<int, List<Bitmap>>();
                if (imageDict != null && imageDict.Count > 0)
                {
                    System.Windows.Forms.FolderBrowserDialog folderBrowser = new System.Windows.Forms.FolderBrowserDialog();
                    if (folderBrowser.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        string choosePath = folderBrowser.SelectedPath;
                        string openPath = choosePath;
                        try
                        {
                            foreach (int pageIndex in imageDict.Keys)
                            {
                                List<Bitmap> imageList = imageDict[pageIndex];
                                foreach (Bitmap image in imageList)
                                {
                                    string savePath = System.IO.Path.Combine(choosePath, Guid.NewGuid() + ".jpg");
                                    image.Save(savePath, System.Drawing.Imaging.ImageFormat.Jpeg);
                                    openPath = savePath;
                                }
                            }
                            Process.Start("explorer", "/select,\"" + openPath + "\"");
                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }
            }
        }

        private void ImageClipBtn_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void OpacityComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ComboBoxItem selectItem = OpacityComboBox.SelectedItem as ComboBoxItem;
            if (selectItem != null && selectItem.Content != null)
            {
                if (double.TryParse(selectItem.Content.ToString().TrimEnd('%'), out double newOpacity))
                {
                    OpacityTextBox.Text = selectItem.Content.ToString();
                    ImasgeOpacitySlider.Value = newOpacity / 100.0;
                }
            }
        }

        public void SetImageThumb()
        {
            //if (PDFView != null && EditEvent!=null)
            //{
            //    try
            //    {
            //        Dictionary<int, List<Bitmap>> imageDict = PDFView.GetSelectedImages();
            //        foreach (int pageIndex in imageDict.Keys)
            //        {
            //            List<Bitmap> imageList = imageDict[pageIndex];
            //            if (imageList.Count > 0)
            //            {
            //                Bitmap bitmapImage = imageList[0];
            //                MemoryStream memoryStream = new MemoryStream();

            //                bitmapImage.Save(memoryStream, bitmapImage.RawFormat);
            //                BitmapImage imageShow = new BitmapImage();
            //                imageShow.BeginInit();
            //                imageShow.StreamSource = memoryStream;
            //                imageShow.EndInit();
            //                ImageThumbUI.Source = imageShow;
            //                break;
            //            }
            //        } 
            //    }
            //    catch (Exception ex)
            //    {

            //    }
            //}
        }

        public void SetImageTransparency(double transparency)
        {
            ImasgeOpacitySlider.Value = transparency / 255D;
            OpacityTextBox.Text = string.Format("{0}%", (int)(Math.Round(ImasgeOpacitySlider.Value * 100)));
        }

        private void GetImageArea(out CPDFEditImageArea imageArea,out CPDFPage pdfPage, out CPDFEditPage editPage)
        {
            imageArea = null;
            editPage = null;
            pdfPage=null;
            if (ToolView == null || EditEvent == null)
            {
                return;
            }

            try
            {
                CPDFViewer pdfViewer = ToolView.GetCPDFViewer();
                CPDFDocument pdfDoc = pdfViewer.GetDocument();
                pdfPage = pdfDoc.PageAtIndex(EditEvent.PageIndex);
                editPage = pdfPage.GetEditPage();
                List<CPDFEditArea> editAreas = editPage.GetEditAreaList();
                if (editAreas != null && editAreas.Count > EditEvent.EditIndex)
                {
                    imageArea = editAreas[EditEvent.EditIndex] as CPDFEditImageArea;
                }
            }
            catch (Exception ex)
            {

            }
        }

    }
}
