using PDF_Office.Model.Dialog.ToolsDialogs;
using ComPDFKit.PDFDocument;
using PDF_Office.Model;
using Prism.Mvvm;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace PDF_Office.ViewModels.Dialog.ToolsDialogs.CompressDialogs
{
    public class CompresProgressBarDialogViewModel : BindableBase, IDialogAware
    {
        #region 参数和属性
        private IntPtr compressingIntpr = IntPtr.Zero;
        private CPDFDocument.GetPageIndexDelegate indexDelegate = null;
        private CPDFDocument tempDocument;
        private string _pageIndex = "0";

        /// <value>
        /// 当前页
        /// </value>
        public string PageIndex
        {
            get { return _pageIndex; }
            set
            {
                SetProperty(ref _pageIndex, value);
            }
        }

        private string _pageNumber = "";
        /// <value>
        /// 总页数
        /// </value>
        public string PageNumber
        {
            get { return _pageNumber; }
            set
            {
                SetProperty(ref _pageNumber, value);
            }
        }
        #endregion

        #region 逻辑函数
        private int GetIndex(int pageindex)
        {
            PageIndex = pageindex.ToString();
            return 0;
        }
        #endregion

        #region 框架行为
        public string Title => "";

        public event Action<IDialogResult> RequestClose;

        public bool CanCloseDialog()
        {
            return true;
        }

        public void OnDialogClosed()
        {
            tempDocument.CompressFile_Cancel(compressingIntpr);
        }

        public async void OnDialogOpened(IDialogParameters parameters)
        {
            CPDFDocument doc = null;
            string filepath = "";
            int compressquality = 45;
            parameters.TryGetValue<CPDFDocument>(ParameterNames.PDFDocument, out doc);
            parameters.TryGetValue<string>(ParameterNames.FilePath, out filepath);
            parameters.TryGetValue<int>("compressDialogModel.CompressQuality", out compressquality);
            if (doc != null)
            {
                PageNumber = doc.PageCount.ToString();
                CPDFDocument document = CPDFDocument.InitWithFilePath(doc.FilePath);
                indexDelegate += GetIndex;
                compressingIntpr = document.CompressFile_Init(compressquality, indexDelegate);
                //GC.KeepAlive(indexDelegate);
                tempDocument = document;
                Trace.WriteLine("compressDialogModel.CompressQuality" + compressquality);
                await Task.Run<bool>(() => { return document.CompressFile_Start(compressingIntpr, filepath); });
                RequestClose?.Invoke(new DialogResult(ButtonResult.OK));
                document.Release();
            }
        }
        #endregion
    }
}
