using ComPDFKit.PDFDocument;
using ComPDFKit.PDFPage;
using ComPDFKit.PDFWatermark;
using ComPDFKitViewer;
using ComPDFKitViewer.PdfViewer;
using PDF_Master.EventAggregators;
using PDF_Master.Helper;
using PDF_Master.Model;
using PDF_Master.Model.EditTools.Background;
using PDF_Master.Model.EditTools.Bates;
using PDF_Master.Model.EditTools.Watermark;
using Prism.Commands;
using Prism.Events;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Size = System.Windows.Size;

namespace PDF_Master.ViewModels.EditTools.Background
{
    public class BackgroundDocumentContentViewModel : BindableBase, INavigationAware
    {
        public IEventAggregator eventAggregator;
        public IRegionManager regionManager;
        public CPDFViewer PDFViewer;
        public CPDFDocument Document;
        private ViewContentViewModel viewContentViewModel;
        public EnumDelete EnumDelete = EnumDelete.StatusCreate;
        public CPDFViewer pdfViewer;

        private CPDFBackground background;
        private BackgroundInfo backgroundInfo;

        public bool firstin = true;

        public string ViewerRegionName { get; set; }

        public string unicode = null;
        public string Unicode = null;

        private int _pageSize;
        public int PageRangeNumber
        {
            get { return _pageSize; }
            set { SetProperty(ref _pageSize, value); }
        }

        private int _currentPageIndex;
        public int CurrentPageIndex
        {
            get { return _currentPageIndex; }
            set
            {
                SetProperty(ref _currentPageIndex, value);

            }
        }

        private Visibility _inputIndexBoxVisible = Visibility.Collapsed;
        public Visibility InputIndexBoxVisible
        {
            get
            {
                return _inputIndexBoxVisible;
            }
            set
            {
                SetProperty(ref _inputIndexBoxVisible, value);
            }
        }

        public DelegateCommand<object> ShowInputIndexBoxCommand { set; get; }
        public DelegateCommand<object> GoToPageCommand { set; get; }

        public BackgroundDocumentContentViewModel(IEventAggregator eventAggregator, IRegionManager regionManager)
        {
            this.regionManager = regionManager;
            this.eventAggregator = eventAggregator;
            Unicode = App.mainWindowViewModel.SelectedItem.Unicode;

           ShowInputIndexBoxCommand = new DelegateCommand<object>(ShowInputIndexBox);
            GoToPageCommand = new DelegateCommand<object>(GoToPage);

            eventAggregator.GetEvent<ConfirmEditToolsBackgroundEvent>().Subscribe(ConfirmEditToolsBackground,e=> e== Unicode);
            eventAggregator.GetEvent<SetBackgroundEvent>().Subscribe(SetBackground, e => e.Unicode == Unicode);
            eventAggregator.GetEvent<DeleteBackgroundEvent>().Subscribe(DeleteBackground, e => e.Unicode == Unicode);
            ViewerRegionName = RegionNames.BackgroundViewerRegionName;
        }

        public void ShowInputIndexBox(object obj)
        {
            if (obj != null)
            {
                InputIndexBoxVisible = Visibility.Visible;
            }
        }

        public void GoToPage(object obj)
        {
            
            if (obj != null)
            {
                var args = obj as TextBox;
                if (args.Text == null)
                {
                    return;
                }
                try
                {
                    if (int.Parse(args.Text) > 0 && int.Parse(args.Text) <= PDFViewer.Document.PageCount && Regex.Match(args.Text, "^\\d+$").Success)
                    {
                        PDFViewer.GoToPage(int.Parse(args.Text) - 1);
                        InputIndexBoxVisible = Visibility.Collapsed;
                    }
                }
                catch
                {
                    PDFViewer.GoToPage(1);
                    InputIndexBoxVisible = Visibility.Collapsed;
                }
            }
        }

        public void ConfirmEditToolsBackground(string unicode)
        {
            if (EnumDelete == EnumDelete.StatusDeleteAll)
            {
                PDFViewer.Document.GetBackground().Clear();
            }

            if (backgroundInfo != null)
            {
                CreateBackground(viewContentViewModel.PDFViewer.Document);
            }
            viewContentViewModel.PDFViewer.UndoManager.CanSave = true;
        }

        public void DeleteBackground(EnumDeleteUnicode enumDeleteunicode)
        {
            if(enumDeleteunicode.Status == EnumDelete.StatusDeleteAll)
            {
                EnumDelete enumDelete = enumDeleteunicode.Status;
                EnumDelete = enumDelete;
                PDFViewer.Document.GetBackground().Clear();
                PDFViewer.Document.ReleasePages();
                PDFViewer.ReloadDocument();
            }
        }
        

        public void SetBackground(BackgroundInfoUnicode backgroundInfounicode)
        {
            EnumDelete = EnumDelete.StatusCreate;
            PDFViewer.Document.GetBackground().Clear();
            PDFViewer.Document.ReleasePages();
            PDFViewer.ReloadDocument();
            BackgroundInfo backgroundInfo = backgroundInfounicode.Status;
            EditToolsHelper.GetPageRange(backgroundInfo.PageRangeIndex, PDFViewer.Document, ref backgroundInfo.PageRange, backgroundInfo.PageRange);
            this.backgroundInfo = backgroundInfo;
            PDFViewer.InvalidChildVisual(false);
        }

        public void CreateBackground(CPDFDocument document, bool IsNewDoc = false)
        {
            if (backgroundInfo != null)
            {
                background = document.GetBackground();
                if (backgroundInfo.BackgroundType == C_Background_Type.BG_TYPE_COLOR)
                {
                    background.SetBackgroundType(C_Background_Type.BG_TYPE_COLOR);
                    background.SetColor(backgroundInfo.Color);
                }
                else
                {
                    background.SetBackgroundType(C_Background_Type.BG_TYPE_IMAGE);
                    background.SetImage(backgroundInfo.ImageArray, backgroundInfo.ImageWidth, backgroundInfo.ImageHeight, ComPDFKit.Import.C_Scale_Type.fitCenter);
                }
                if (!backgroundInfo.IsRelativeScale)
                {
                    background.SetScale(1);
                }
                else
                {
                    background.SetScale((float)(backgroundInfo.Scale / 100));
                }
                background.SetRotation((float)((backgroundInfo.Rotation / 180) * Math.PI ));
                background.SetOpacity((byte)(((float)backgroundInfo.Opacity / 100) * 255));
                background.SetVertalign(backgroundInfo.Vertalign);
                background.SetHorizalign(backgroundInfo.Horizalign);
                background.SetXOffset(backgroundInfo.HorizOffset);
                background.SetYOffset(backgroundInfo.VertOffset);
                background.SetAllowsPrint(true);
                background.SetAllowsView(true);
                if (IsNewDoc) { background.SetPages("0"); }
                else
                {
                    background.SetPages(backgroundInfo.PageRange);
                }
                background.Update();
            }
        }


        private void UndoManager_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {

        }

        private void CurrentViewer_CustomDrawHandler(object sender, CustomDrawData e)
        {
            if (e.DrawPages.Count > 0 && e.DrawContext != null)
            {
                List<int> PageIndexLists = new List<int>();
                foreach (DrawPageData drawPageData in e.DrawPages)
                {
                    if (backgroundInfo != null)
                    {
                        char[] enumerationSeparator = new char[] { ',' };
                        char[] rangeSeparator = new char[] { '-' };
                        if (CommonHelper.GetPagesInRange(ref PageIndexLists, backgroundInfo.PageRange, Document.PageCount, enumerationSeparator, rangeSeparator, true))
                        { //TODO
                            if (PageIndexLists.Contains(drawPageData.PageIndex - 1))
                            {
                                WriteableBitmap backgroundBitmap = GetBackground(PDFViewer.Document, e.Zoom, drawPageData.PageIndex);
                                e.DrawContext.DrawImage(backgroundBitmap, drawPageData.PageBound);
                            }
                        }
                    }
                }
            }
            CurrentPageIndex = PDFViewer.CurrentIndex + 1;
        }

        private WriteableBitmap GetBackground(CPDFDocument oldDoc, double zoom, int pageIndex)
        {
            Size pageSize = oldDoc.GetPageSize(pageIndex);

            CPDFDocument newDoc = CPDFDocument.CreateDocument();
            newDoc.InsertPage(0, pageSize.Width, pageSize.Height, null);
            CreateBackground(newDoc, true);
            CPDFPage newPage = newDoc.PageAtIndex(0);
            double scale = 96.0 / 72.0;
            zoom = zoom * 1.5;
            Rect renderRect = new Rect(0, 0, (int)(pageSize.Width * scale), (int)(pageSize.Height * scale));
            byte[] imageArray = new byte[(int)(renderRect.Width * renderRect.Height * 4)];
            newPage.RenderPageBitmapWithMatrix(1/(float)zoom, renderRect, 0x00FFFFFF, imageArray, 1, true);
            WriteableBitmap WirteBitmap = new WriteableBitmap((int)renderRect.Width, (int)renderRect.Height, 96, 96, PixelFormats.Bgra32, null);
            WirteBitmap.WritePixels(new Int32Rect(0, 0, (int)renderRect.Width, (int)renderRect.Height), imageArray, WirteBitmap.BackBufferStride, 0);
            newDoc.Release();
            return WirteBitmap;
        }

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {

        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out pdfViewer);
            navigationContext.Parameters.TryGetValue<ViewContentViewModel>(ParameterNames.ViewContentViewModel, out viewContentViewModel);
            if (pdfViewer != null)
            {
                if (!regionManager.Regions[ViewerRegionName].Views.Contains(PDFViewer))
                {
                    PDFViewer = new CPDFViewer();
                    PDFViewer.InitDocument(pdfViewer.Document);
                    Document = PDFViewer.Document;
                    PDFViewer.CustomDrawHandler += CurrentViewer_CustomDrawHandler;
                    PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
                    regionManager.AddToRegion(ViewerRegionName, PDFViewer);
                    PDFViewer.SetAnnotInteraction(!PDFViewer.GetAnnotInteraction());
                    PDFViewer.Load();
                    PDFViewer.ChangeViewMode(ViewMode.Single);
                    PDFViewer.SetMouseMode(MouseModes.PanTool);
                    PageRangeNumber = PDFViewer.Document.PageCount;
                    PDFViewer.Zoom(0.5);
                }
            }
        }
    }
}