using GalaSoft.MvvmLight.Command;
using Install.Core.Common;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows;
using Update.Core;

namespace Update.View
{
    /// <summary>
    /// PgDownload.xaml 的交互逻辑
    /// </summary>
    public partial class WdDownload : Window
    {
        WdDownloadVm viewModel;

        public WdDownload()
        {
            InitializeComponent();

            viewModel = new WdDownloadVm();
        }

        public void Init()
        {
            viewModel.Init();
            this.DataContext = viewModel;

            viewModel.DownloadNewestInstallZip();

        }
    }
    public class WdDownloadVm : INotifyPropertyChanged
    {
        InstallWizard installWizard;

        public event PropertyChangedEventHandler PropertyChanged;

        public bool IsReady { get; private set; } = false;
        
        public string Msg { get; private set; }
        public InstallWizard InstallWizard => installWizard;

        public RelayCommand ExecCmd { get; set; }
        public RelayCommand CancelCmd { get; set; }

        public WdDownloadVm()
        {
            ExecCmd = new RelayCommand(Exec);
            CancelCmd = new RelayCommand(Cancel);
        }



        public void Init()
        {
            installWizard = Application.Current.Properties[nameof(InstallWizard)] as InstallWizard;
            Msg = $"下载 {installWizard.NewestInstallZipVersionInfo.InstallZipUrl}";

        }
        public async void DownloadNewestInstallZip()
        {
            var ret = await installWizard.DownloadNewestInstallZip();
            Msg = installWizard.DownloadInfo_ErrMsg;
            if (ret == true)
            {

                //解压
                //获取当前 exe 目录

                Msg = "开始解压......";
                await Task.Factory.StartNew(() =>
                {
                    SeverZipExt.Uncompress(installWizard.NewestInstallZipPath + ".7z", installWizard.NewestInstallZipPath);
                });
                Msg = "解压完成!!!";
                IsReady = true;
            }
        }
        private void Cancel()
        {
            //关闭当前

            Application.Current.Shutdown();
        }

        private void Exec()
        {
            //关闭当前,进入新的安装包,运行
            string exePath = System.IO.Path.Combine(installWizard.NewestInstallZipPath, "install.exe");
            CMD.RunExe(exePath);
            Application.Current.Shutdown();
        }
    }
}