using ComPDFKit.PDFDocument;
using ComPDFKit.PDFPage;
using ComPDFKit.PDFWatermark;
using ComPDFKitViewer;
using ComPDFKitViewer.PdfViewer;
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 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_Office.ViewModels.EditTools.Background
{
    public class BackgroundDocumentContentViewModel : BindableBase, INavigationAware
    {
        public IEventAggregator eventAggregator;
        public IRegionManager regionManager;
        public CPDFViewer PDFViewer;
        public CPDFDocument Document;
        private ViewContentViewModel viewContentViewModel;
        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);
            eventAggregator.GetEvent<SetBackgroundEvent>().Subscribe(SetBackground, 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;
                }
                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;
                }
            }
        }

        public void ConfirmEditToolsBackground()
        {
            if (backgroundInfo != null)
            {
                CreateBackground(viewContentViewModel.PDFViewer.Document);
            }
        }

        public void SetBackground(BackgroundInfoUnicode backgroundInfounicode)
        {
            BackgroundInfo backgroundInfo = backgroundInfounicode.Status;
            this.backgroundInfo = backgroundInfo;
            CreateBackground(PDFViewer.Document);
            PDFViewer.InvalidChildVisual(false);
            PDFViewer.Document.ReleasePages();
            PDFViewer.ReloadDocument();
        }

        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);
                }

                background.SetScale(1);
                background.SetRotation(backgroundInfo.Rotation);
                background.SetOpacity(backgroundInfo.Opacity);
                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 * scale;
            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((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);
            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);
            navigationContext.Parameters.TryGetValue<string>("UniCode", out unicode);
            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.Default);
                    PageRangeNumber = PDFViewer.Document.PageCount;
                }
            }
        }
    }
}











