using CTZLauncher.Modules.CTZServer;
using CTZLauncher.Tools;
using KMCCC.Authentication;
using KMCCC.Launcher;
using KMCCC.Tools;
using LitJson;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;

namespace CTZLauncher
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        LauncherCore launcher = null;
        LaunchOptions option = new LaunchOptions();
        string serveraddress = ConfigurationManager.AppSettings["Server"];
        int serverport = 25580;

        #region 初始化部分
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Initialized(object sender, EventArgs e)
        {
            if (!Directory.Exists(".minecraft"))
            {
                Directory.CreateDirectory(".minecraft");
            }
            launcher = LauncherCore.Create(".minecraft");
        }
        #endregion

        #region 登录界面
        private void barclick_MouseDown(object sender, MouseButtonEventArgs e)
        {
            Label bar = (Label)sender;
            MessageBox.Show(bar.Name);
            switch (bar.Name.Substring(4))
            {
                case "l1":
                    break;
                case "l2":
                    break;
                case "l3":
                    break;
                case "l4":
                    break;
                case "r1":
                    break;
                case "r2":
                    break;
                case "r3":
                    break;
                case "r4":
                    break;
            }
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            if (username.Text.Length == 0 || password.Text.Length == 0)
            {
                MessageBox.Show("请输入账号密码!");
                return;
            }
            Login.IsEnabled = false;
            CTZAuthenticator auth = new CTZAuthenticator(username.Text, password.Text, serveraddress, serverport);
            try
            {
                if (auth.isLogin())
                {
                    MessageBox.Show("当前玩家已登录服务器!");
                }
                else
                {
                    if (!auth.Login())
                    {
                        if (!auth.isRegistered())
                            MessageBox.Show("该用户名未注册 请先注册!");
                        else
                            MessageBox.Show("登录失败 账号不存在 或 密码错误 !");
                    }
                    else
                    {
                        ServerWindow.Visibility = Visibility.Visible;
                        RotateTransform rtf = new RotateTransform();
                        ServerWindow.RenderTransform = rtf;
                        LoginWindow.RenderTransform = rtf;
                        DoubleAnimation dbAscending = new DoubleAnimation(0, 360, new Duration(TimeSpan.FromSeconds(0.75)));
                        dbAscending.RepeatBehavior = new RepeatBehavior(1);
                        rtf.BeginAnimation(RotateTransform.AngleProperty, dbAscending);
                        CTZServer areas = JsonMapper.ToObject<CTZServer>(auth.getServerList().ToLower());
                        LoadAreas(areas);
                    }
                }
            }
            catch (ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                Login.IsEnabled = true;
            }
        }

        private void outline_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (e.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        private void close_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void maxmem_TextChanged(object sender, TextChangedEventArgs e)
        {
            //屏蔽中文输入和非法字符粘贴输入
            TextBox textBox = sender as TextBox;
            TextChange[] change = new TextChange[e.Changes.Count];
            e.Changes.CopyTo(change, 0);

            int offset = change[0].Offset;
            if (change[0].AddedLength > 0)
            {
                double num = 0;
                if (!Double.TryParse(textBox.Text, out num))
                {
                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                    textBox.Select(offset, 0);
                }
            }
        }

        private void register_Click(object sender, RoutedEventArgs e)
        {


        }
        #endregion

        #region 服务器选择与启动
        private void LoadAreas(CTZServer areas)
        {
            for (int i = 0; i < areas.Areas.Count; i++)
            {
                Area area = areas.Areas[i];
                Button arearb = GameArea.FindName("a" + i) as Button;
                arearb.Content = area.Name;
                arearb.Visibility = Visibility.Visible;
                arearb.Tag = area.Servers;
            }
            for (int i = areas.Areas.Count; i < 8; i++)
            {
                Button arearb = GameArea.FindName("a" + i) as Button;
                arearb.Visibility = Visibility.Hidden;
            }
        }

        private void LoadServers(List<Server> servers)
        {
            for (int i = 0; i < servers.Count; i++)
            {
                Server server = servers[i];
                Button serverrb = GameArea.FindName("s" + i) as Button;
                serverrb.Content = server.Name;
                serverrb.Visibility = Visibility.Visible;
                serverrb.Tag = server;
            }
            for (int i = servers.Count; i < 12; i++)
            {
                Button serverrb = GameArea.FindName("s" + i) as Button;
                serverrb.Visibility = Visibility.Hidden;
            }
        }

        private void area_Click(object sender, RoutedEventArgs e)
        {
            Button arb = (Button)sender;
            LoadServers((List<Server>)arb.Tag);
        }

        private void server_Click(object sender, RoutedEventArgs e)
        {
            Button srb = (Button)sender;
            Server server = (Server)srb.Tag;
            option.Server = new ServerInfo
            {
                Address = server.Address,
                Port = server.Port
            };
            option.Version = launcher.GetVersion(server.Version);
            serverinfo.Content = server.Info;
            selserver.Content = server.Name;
            needclient.Content = server.Version;
            online.Content = "获取中...";
            MinecraftServer ms = new MinecraftServer(server.Address, server.Port);
            var info = ms.DoAsync();
            if (info != null)
                online.Content = info.Players.Online + "/" + info.Players.Max;
            else
                online.Content = "获取失败!";
        }

        private void StartGame_Click(object sender, RoutedEventArgs e)
        {
            if (option.Version == null)
            {
                MessageBoxResult result = MessageBox.Show("是否下载服务器所需要的客户端版本?", "缺少客户端", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {

                }
                return;
            }
            Console.WriteLine("启动游戏");
            option.Mode = LaunchMode.MCLauncher;
            option.MaxMemory = 2048;
            option.Authenticator = new OfflineAuthenticator(username.Text); // 离线模式
            launcher.JavaPath = SystemTools.FindJava().First();
            launcher.GameLog += launcher_GameLog;
            launcher.GameStart += Launcher_GameStart;
            launcher.Launch(option);
        }

        private void Launcher_GameStart(LaunchHandle arg1, string arg2)
        {
            string title = selserver.Content.ToString() + " - " + username.Text;
            arg1.SetTitle(title);
        }

        void launcher_GameLog(LaunchHandle arg1, string log)
        {
            Console.WriteLine(log);
        }
        #endregion

        private void username_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                password.Focus();
        }

        private void password_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                Login_Click(sender, e);
        }
    }
}
