using ComPDFKit.PDFDocument;
using ComPDFKit.PDFPage;
using ComPDFKit.PDFWatermark;
using ComPDFKitViewer.PdfViewer;
using PDF_Office.CustomControl;
using PDF_Office.EventAggregators;
using PDF_Office.Helper;
using PDF_Office.Model;
using PDF_Office.Model.EditTools.Background;
using PDF_Office.Model.EditTools.Watermark;
using PDF_Office.Properties;
using PDF_Office.ViewModels.Tools;
using PDFSettings;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace PDF_Office.ViewModels.EditTools.Watermark
{
    public class WatermarkTemplateListFileContentViewModel : BindableBase, INavigationAware
    {
        private readonly IEventAggregator eventAggregator;

        private CPDFViewer CurrentPDFViewer;

        public WatermarkInfo WatermarkInfo = new WatermarkInfo();

        public WatermarkItem WatermarkItem = new WatermarkItem();

        public int TemplateIndex = 0;
        public ObservableCollection<WatermarkItem> watermarkModFileCollection = new ObservableCollection<WatermarkItem>();
        public ObservableCollection<WatermarkItem> WatermarkModFileCollection
        {
            get { return watermarkModFileCollection; }
            set
            {
                watermarkModFileCollection = value;
                RaisePropertyChanged();
            }
        }

        private Visibility _createTemplateVisible;
        public Visibility CreateTemplateVisible
        {
            get { return _createTemplateVisible; }
            set { SetProperty(ref _createTemplateVisible, value); }
        }

        private ImageSource _imageSource;
        public ImageSource ImageSource
        {

            get { return _imageSource; }
            set { SetProperty(ref _imageSource, value); }
        }

        public DelegateCommand AddTemplateCommand { get; set; }
        public DelegateCommand<object> DeleteTemplateItemCommand { get; set; }
        public DelegateCommand<object> EditTemplateItemCommand { get; set; }
        public DelegateCommand DeleteAllTemplateItemCommand { get; set; }
        public DelegateCommand<object> SelectTemplateItemCommand { get; set; }

        public string Unicode = null;

        public WatermarkTemplateListFileContentViewModel(IEventAggregator eventAggregator)
        {
            this.eventAggregator = eventAggregator;
            Unicode = App.mainWindowViewModel.SelectedItem.Unicode;
            AddTemplateCommand = new DelegateCommand(AddTemplate);
            DeleteTemplateItemCommand = new DelegateCommand<object>(DeleteTemplateItem);
            EditTemplateItemCommand = new DelegateCommand<object>(RequestEditTemplateItem);
            DeleteAllTemplateItemCommand = new DelegateCommand(DeleteAllTemplateItem);
            SelectTemplateItemCommand = new DelegateCommand<object>(SelectTemplateItem);

            eventAggregator.GetEvent<CurrentWatermarkPDFViewerEvent>().Subscribe(CurrentWatermarkPDFViewer, e => e.Unicode == Unicode);
            eventAggregator.GetEvent<SaveEditedWatermarkTemplateItemEvent>().Subscribe(SaveEditedWatermarkTemplateItem, e => e.Unicode == Unicode);

        }
        public void CurrentWatermarkPDFViewer(CPDFViewerUnicode cPDFViewerunicode)
        {
            CurrentPDFViewer = cPDFViewerunicode.Status;
        }

        private void CheckTemplateListIsEmpty(List<WatermarkItem> watermarkTemplateList)
        {
            if (watermarkTemplateList.Count() == 0)
            {
                CreateTemplateVisible = Visibility.Visible;
            }
            else
            {
                CreateTemplateVisible = Visibility.Collapsed;
            }
        }

        private void GetWatermarkSource()
        {
            List<WatermarkItem> watermarkModTextTemplateList = new List<WatermarkItem>();
            for (int temp = 0; temp < Settings.Default.WatermarkTemplateList.Count; temp++)
            {
                if (Settings.Default.WatermarkTemplateList[temp].type == ComPDFKit.PDFWatermark.C_Watermark_Type.WATERMARK_TYPE_IMG)
                {
                    watermarkModTextTemplateList.Add(Settings.Default.WatermarkTemplateList[temp]);

                }
            }
            WatermarkModFileCollection = new ObservableCollection<WatermarkItem>(watermarkModTextTemplateList);
            CheckTemplateListIsEmpty(watermarkModTextTemplateList);
        }



        private void InitWatermarkTemplateList()
        {
            if (Settings.Default.WatermarkTemplateList == null)
            {
                Settings.Default.WatermarkTemplateList = new WatermarkTemplateList();
            }
            GetWatermarkSource();
        }


        public void AddTemplate()
        {
            this.eventAggregator.GetEvent<EnterTemplateListOrCreateEvent>().Publish(new EnumTemplateListOrCreateUnicode
            {
                Unicode = Unicode,
                Status = EnumTemplateListOrCreate.StatusCreate
            });
        }

        public void DeleteTemplateItem(object e)
        {
            var btn = e as System.Windows.Controls.Control;
            if (btn == null)
            {
                return;
            }
            var template = btn.DataContext as WatermarkItem;
            if (template == null)
            {
                return;
            }

            Settings.Default.WatermarkTemplateList.Remove(template);
            Settings.Default.Save();

            WatermarkModFileCollection.Remove(template);
            GetWatermarkSource();

        }

        public void DeleteAllTemplateItem()
        {
            while (Settings.Default.WatermarkTemplateList.Count != 0)
            {
                int temp = 0;
                var template = Settings.Default.WatermarkTemplateList[temp];
                if (template.type == ComPDFKit.PDFWatermark.C_Watermark_Type.WATERMARK_TYPE_IMG)
                {
                    Settings.Default.WatermarkTemplateList.Remove(template);
                    Settings.Default.Save();
                    WatermarkModFileCollection.Remove(template);
                }
            }
            GetWatermarkSource();
        }

        public void SaveEditedWatermarkTemplateItem(WatermarkItemUnicode watermarkItemunicode)
        {
            WatermarkItem watermarkItem = watermarkItemunicode.Status;
            Settings.Default.WatermarkTemplateList[TemplateIndex] = watermarkItem;
            Settings.Default.Save();
            GetWatermarkSource();
        }


        public void RequestEditTemplateItem(object e)
        {
            var control = e as Control;
            if (control == null)
            {
                return;
            }
            var template = control.DataContext as WatermarkItem;
            if (template == null)
            {
                return;
            }
            TemplateIndex = Settings.Default.WatermarkTemplateList.IndexOf(template);
            template.listIndex = TemplateIndex;
            this.eventAggregator.GetEvent<EditWatermarkTemplateItemEvent>().Publish(new WatermarkItemUnicode
            {
                Unicode = Unicode,
                Status = template
            });
        }

        public void SelectTemplateItem(object e)
        {
            AlertsMessage alertsMessage = new AlertsMessage();
            if (CurrentPDFViewer.Document.GetWatermarkCount() > 0)
            {
                alertsMessage.ShowDialog("文件中已添加水印，您要替换现有的水印吗？", "", "取消", "确定");
                if (alertsMessage.result == ContentResult.Ok)
                {
                    this.eventAggregator.GetEvent<DeleteWatermarkEvent>().Publish(new EnumDeleteUnicode
                    {
                        Unicode = Unicode,
                        Status = EnumDelete.StatusDeleteInitial
                    });
                }
                else
                {
                    this.eventAggregator.GetEvent<DeleteWatermarkEvent>().Publish(new EnumDeleteUnicode
                    {
                        Unicode = Unicode,
                        Status = EnumDelete.StatusCreate
                    });
                }
            }
            var listBox = e as ListBox;
            WatermarkItem WatermarkItem = listBox.SelectedItem as WatermarkItem;
            SendTemplateItemToDocument(WatermarkItem);
        }

        public void ConvertItemToInfo(WatermarkItem watermarkItem, ref WatermarkInfo watermarkInfo)
        {
            if (watermarkItem != null)
            {
                watermarkInfo.WatermarkType = watermarkItem.type;
                FileInfo file = new FileInfo(watermarkItem.imagepath);
                if (file.Exists)
                {
                    if (file.Extension == ".pdf")
                    {
                        GetBitmapFromDocment(watermarkItem.imagepath);
                    }
                    else
                    {
                        EditToolsHelper.ChooseFile(watermarkItem.imagepath, ref WatermarkInfo);
                    }
                }
                else
                {
                    watermarkInfo.WatermarkType = ComPDFKit.PDFWatermark.C_Watermark_Type.WATERMARK_TYPE_UNKWON;
                    MessageBoxEx.Show("原路径为：" + watermarkItem.imagepath + ",该文件不存在");
                }
                watermarkInfo.WatermarkHorizalign = watermarkItem.horizalign;
                watermarkInfo.WatermarkVertalign = watermarkItem.vertalign;
                watermarkInfo.Isfull = watermarkItem.isFullScreen;
                watermarkInfo.IsFront = watermarkItem.isfront;
                watermarkInfo.ImageSize = watermarkItem.imageSize;
                watermarkInfo.Opacity = watermarkItem.opacity;
                watermarkInfo.Rotation = watermarkItem.rotation;
                watermarkInfo.VertOffset = watermarkItem.vertOffset;
                watermarkInfo.HorizOffset = watermarkItem.horizOffset;
                watermarkInfo.VerticalSpacing = watermarkItem.verticalSpacing;
                watermarkInfo.HorizontalSpacing = watermarkItem.horizontalSpacing;
                EditToolsHelper.GetPageRange(watermarkItem.pageRangeIndex, CurrentPDFViewer.Document, ref WatermarkInfo.PageRange, watermarkItem.pageRange);
            }
        }

        public async void GetBitmapFromDocment(string filePath)
        {
            CPDFDocument document = CPDFDocument.InitWithFilePath(filePath);
            CPDFPage page = document.PageAtIndex(0);
            byte[] bmp_data = new byte[(int)page.PageSize.Width * (int)page.PageSize.Height * 4];
            await Task.Run(delegate
            {
                page.RenderPageBitmap(0, 0, (int)page.PageSize.Width, (int)page.PageSize.Height, 0xffffffff, bmp_data, 1);
            });
            WatermarkInfo.ImageArray = bmp_data;
            WatermarkInfo.ImageWidth = (int)page.PageSize.Width;
            WatermarkInfo.ImageHeight = (int)page.PageSize.Height;
            document.ReleasePages();
            document.Release();
        }

        public void SendTemplateItemToDocument(WatermarkItem WatermarkItem)
        {
            ConvertItemToInfo(WatermarkItem, ref WatermarkInfo);
            eventAggregator.GetEvent<SetWatermarkEvent>().Publish(new WatermarkInfoUnicode
            {
                Unicode = Unicode,
                Status = WatermarkInfo
            });
        }


        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            InitWatermarkTemplateList();
        }
    }
}
