using ComPDFKitViewer.PdfViewer;
using Microsoft.Win32;
using PDF_Office.CustomControl;
using PDF_Office.EventAggregators;
using PDF_Office.Views;
using Prism.Commands;
using Prism.Events;
using Prism.Ioc;
using Prism.Mvvm;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using PDF_Office.Model;
using System.ComponentModel;
using PDF_Office.Helper;
using PDFSettings.Settings;

namespace PDF_Office.ViewModels
{
    public class MainContentViewModel : BindableBase, INavigationAware
    {
        private string fileName = "Home";

        public string FileName
        {
            get { return fileName; }
            set { SetProperty(ref fileName, value); }
        }

        private string filePath;

        public string FilePath
        {
            get { return filePath; }
            set
            {
                SetProperty(ref filePath, value);
                if (!string.IsNullOrEmpty(filePath))
                {
                    FileName = System.IO.Path.GetFileName(filePath);
                }

            }
        }

        private Visibility fileChanged = Visibility.Collapsed;

        public Visibility FileChanged
        {
            get { return fileChanged; }
            set { SetProperty(ref fileChanged, value); }
        }

        public CPDFViewer PDFViewer { get; set; }


        public DelegateCommand<object> CloseTab { get; set; }

        public DelegateCommand<object> Loaded { get; set; }


        private string regionName;

        public string MainContentRegionName
        {
            get { return regionName; }
            set { SetProperty(ref regionName, value); }
        }

        public IRegionManager toolregion;

        public IEventAggregator eventer;

        public IContainerProvider container;

        public IDialogService dialogs;

        public MainContentViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IContainerProvider containerProvider, IDialogService dialogService)
        {
            toolregion = regionManager;
            eventer = eventAggregator;
            container = containerProvider;
            dialogs = dialogService;

            CloseTab = new DelegateCommand<object>(CloseTabItem);

            MainContentRegionName = Guid.NewGuid().ToString();

            System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
            {
                NavigationParameters parameters = new NavigationParameters
                {
                    {
                        "MainViewModel", this
                    }
                };
                if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
                    toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
            }));
        }

        private void CloseTabItem(object item)
        {
            App.mainWindowViewModel?.CloseTabItem(item);
            App.OpenedFileList.Remove(FilePath);
        }


        public void OpenFile(string filePath)
        {
            var result = LoadFileFormPath(filePath);
            if (!result)
            {
                return;
            }
            FilePath = filePath;

            NavigationParameters parameters = new NavigationParameters {
                { ParameterNames.MainViewModel, this },
                { ParameterNames.PDFViewer,PDFViewer}
            };
            System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
                {
                    if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
                        toolregion.RequestNavigate(MainContentRegionName, "ViewContent", parameters);
                }));

            //检查是否是新文档
            OpenFileInfo isnew = SettingHelper.GetFileInfo(filePath);
            if (isnew == null)
            {
                isNewDocument = true;
                if(App.OpenedFileList.Contains(filePath) == false)
                    App.OpenedFileList.Add(filePath);
                SettingHelper.SortRecentOpenFiles(filePath);
            }



        }
        private bool isNewDocument = false;
        /// <summary>
        /// 从文件路径创建PDFViewer对象，已包含文档解密逻辑
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private bool LoadFileFormPath(string path)
        {
            PDFViewer = new CPDFViewer();
            PDFViewer.InitDocument(path);
            PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
            if (PDFViewer.Document == null)
            {
                //MessageBoxEx.Show(App.MainPageLoader.GetString("Main_OpenFileFailedWarning"));
                return false;
            }
            else
            {
                if (PDFViewer.Document.IsLocked)
                {
                    DialogParameters value = new DialogParameters();
                    value.Add(ParameterNames.PDFDocument, PDFViewer.Document);
                    dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value, e =>
                    {
                        if (e.Result == ButtonResult.OK)
                        {
                            if (e.Parameters.ContainsKey(ParameterNames.PassWord) && e.Parameters.GetValue<string>(ParameterNames.PassWord) != null)
                            {
                                PDFViewer.Tag = e.Parameters.GetValue<string>(ParameterNames.PassWord).ToString();
                            }
                        }
                    });

                    if (PDFViewer.Document.IsLocked)
                    {
                        //未成功解密文档时，释放Document对象，返回
                        PDFViewer.Document.Release();
                        return false;
                    }
                }
            }

            PDFViewer.Load();

            if (App.mainWindowViewModel != null)
            {
                App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
            }
            App.OpenedFileList.Add(path);
            return true;
        }

        private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            if (e.PropertyName == "CanSave")
            {
                if (PDFViewer.UndoManager.CanSave)
                {
                    FileChanged = Visibility.Visible;
                }
            }
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.Count <= 0)
                return;
            var filepath = navigationContext.Parameters[ParameterNames.FilePath];
            if (filepath != null)
            {
                OpenFile(filepath.ToString());
            }
        }

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

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
        }
    }
}
