using CommonFroms.G2D;
using CommonLang.IO;
using CommonLang.Log;
using CommonLang.Xml;
using CommonUI_Unity3D.Impl;
using MPQ.FileSystem;
using MPQ.Resource;
using MPQ.Updater;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using XmdsBattleClientBot;
using XmdsBattleClientBot.Bot;

namespace XmdsBattleClientWin32
{
    public partial class FormLauncher : Form
    {
        public static BotConfig LastConfig { get; private set; }
        private static MPQFileSystem FileSystem { get; set; }
        private BotConfig Config = new BotConfig();

        private Action<FormLauncher, BotConfig> m_OnStart;
        public event Action<FormLauncher, BotConfig> OnStart { add { m_OnStart += value; } remove { m_OnStart -= value; } }

        public FormLauncher()
        {
            InitializeComponent();
            ListLogger.EnableConsole = false;
        }
        private void FormLauncher_Load(object sender, EventArgs e)
        {
            try
            {
                var saved = XmlUtil.LoadXML(Application.StartupPath + "/bot_config.xml");
                if (saved != null)
                {
                    Config = XmlUtil.XmlToObject<BotConfig>(saved);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show("加载配置失败: " + err.Message);
                this.Show();
                return;
            }
            this.prop_Config.SetSelectedObject(Config);
        }
        private void btn_Start_Click(object sender, EventArgs e)
        {
            Start();
        }
        public void Start()
        {
            var config = XmlUtil.CloneObject(Config);
            try
            {
                var save = XmlUtil.ObjectToXml(Config);
                XmlUtil.SaveXML(Application.StartupPath + "/bot_config.xml", save);
                if (config.UseMPQ)
                {
                    var task = new DownloadTask(config);
                    var download = new G2DProgressDialog(task);
                    download.ShowDialog();
                    task.InitMPQ(config);
                }
                this.Hide();
                if (config.UseMPQ)
                {
                    config.DataRoot = "mpq:///GameEditor/data";
                    config.LuaRoot = "mpq:///ui_edit/lua";
                }
                else if (!Directory.Exists(config.DataRoot))
                {
                    MessageBox.Show("资源地址不存在: " + config.DataRoot);
                    return;
                }
                BotClientManager.Init(config);
            }
            catch (Exception err)
            {
                MessageBox.Show("初始化失败: " + err);
                this.Show();
                return;
            }
            LastConfig = config;
            if (m_OnStart != null) { m_OnStart.Invoke(this, config); }
        }
        private class DownloadTask : IProgress, MPQUpdaterListener
        {
            private MPQUpdater updater;
            private bool done = false;

            public DownloadTask(BotConfig cfg)
            {
				//http://192.168.4.169/sjcs/res_develop/updates_png/update_version.txt
				var suffix = "updates_pvr/update_version.txt";
				MPQUpdater.ZIP_EXT = ".z";
				updater = new MPQUpdater();
				updater.Init(
					new string[] { cfg.ResourcesURL },
					suffix,
					new DirectoryInfo(Application.StartupPath + "/remote_mpq"),
					new DirectoryInfo(Application.StartupPath + "/local_mpq"),
					false, this);
				updater.Start();
				this.Title = cfg.ResourcesURL + suffix;
			}

            public void onEvent(MPQUpdater updater, MPQUpdaterEvent e)
            {
                if (e.EventType == MPQUpdaterEvent.TYPE_COMPLETE)
                {
                    this.done = true;
                }
            }
            public override void Run()
            {
                while (!done)
                {
                    updater.Update();
                    switch (updater.CurrentStatus)
                    {
                        case MPQUpdater.Status.Downloading:
							this.Text = updater.CurrentStatus + " : " + ""; //updater.CurrentDownloadFile;
                            this.Maximum = (int)((updater.TotalDownloadBytes) / 1024);
                            this.Value = (int)((updater.CurrentDownloadBytes) / 1024);
                            break;
                        case MPQUpdater.Status.Unzipping:
							this.Text = updater.CurrentStatus + " : " + "";// updater.CurrentUnzipFile;
                            this.Maximum = (int)((updater.TotalUnzipBytes) / 1024);
                            this.Value = (int)((updater.CurrentUnzipBytes) / 1024);
                            break;
                        default:
                            this.Text = updater.CurrentStatus.ToString();
                            break;
                    }
                    Thread.Sleep(1);
                }
                updater.Dispose();
                this.IsDone = true;
            }
            public bool InitMPQ(BotConfig cfg)
            {
                if (done)
                {
                    if (FormLauncher.FileSystem != null) { FormLauncher.FileSystem.Dispose(); }
                    FormLauncher.FileSystem = new MPQFileSystem();
                    FormLauncher.FileSystem.init(updater);
                    new MPQResourceLoader(Application.StartupPath, FormLauncher.FileSystem);
                    return true;
                }
                return done;
            }
        }
    }
}