﻿using MaterialSkin.Controls;
using MCServerInfo_2;
using Microsoft.VisualBasic.Devices;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Threading;

namespace NewAlphaBukkit.Forms
{
    public partial class MainForm : MaterialForm
    {
        public Thread StatusInfo;
        public static Thread GetServer;

        public static string InPlayer = ""; static string Motd = ""; public static List<MCServerInfo_2.Player> Player_List; static double? ms = 0;
        static ComputerInfo ComputerInfo = new ComputerInfo();

        /// <summary>
        /// 현재 상태를 폼 화면에 출력시킵니다.
        /// </summary>
        private void T_Status_Tick(object sender, EventArgs e)
        {
            //서버상태 (Motd , Player 등을 설정함)
            if (Motd != "")
            {
                try
                {
                    while (!Motd.Contains("§"))
                    {
                        Motd = Motd.Replace("§" + Microsoft.VisualBasic.Strings.Left(Motd.Split('§')[1], 1), "");
                    }
                }
                catch { }
                Lv_Motd.Text = Motd;
            }
            else
                Lv_Motd.Text = "서버가 닫혀있습니다";

            if (InPlayer != "")
                Lv_Player.Text = InPlayer;
            else
                Lv_Player.Text = "? / ?";

            Lv_SetIP.Text = Setting.SetIP;

            //CPU , RAM 점유율을 계산함
            int CPU = 0; int RAM = 0;
            try
            {
                if (!(Process.GetProcessesByName("java").Length < 1))
                {
                    CPU = (int)PC_CPU.NextValue() / Environment.ProcessorCount;
                    RAM = (int)new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / (int)new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory * 100;
                }
            }
            catch
            {
                CPU = 0;
                RAM = 0;
            }

            int CPURAM = 0; //점유율 계산
            CPURAM = (CPU + RAM) / 2;
            if (CPURAM < 30)
            {
                Lv_CPURAM.Text = "정상";
                Lv_CPURAM.ForeColor = Color.ForestGreen;
            }
            else if (CPURAM >= 60)
            {
                Lv_CPURAM.Text = "높음";
                Lv_CPURAM.ForeColor = Color.Red;
            }
            else
            {
                Lv_CPURAM.Text = "보통";
                Lv_CPURAM.ForeColor = Color.Orange;
            }

            //서버의 응답속도를 출력
            Lv_Sms.Text = (ms == null ? ms.ToString() : "? ms");
            if (ms != null)
            {
                Lv_Sms.Text = ms.ToString() + " ms";
            }
            else
            {
                Lv_Sms.Text = "? ms";
            }

            try
            {
                if (Consoles != null && Consoles.HasExited)
                    Lv_BukkitStatus.Text = "버킷상태 : 닫힘";
                else
                    Lv_BukkitStatus.Text = "버킷상태 : 열림";
            }
            catch
            {
                Lv_BukkitStatus.Text = "버킷상태 : 닫힘";
            }

            Lv_Since.Text = ServerSince.Elapsed.Hours.ToString() + " : " + ServerSince.Elapsed.Minutes.ToString() + " : " + ServerSince.Elapsed.Seconds.ToString();

            if (Setting.Log_Write && LogQu.Count != 0)
            {
                using (StreamWriter LogFile = new StreamWriter(new FileStream(Setting.DataPath + "\\servers\\" + name + "\\AlphaBukkitLog\\" + Setting.Date + ".txt", FileMode.Append)))
                {
                    while (LogQu.Count != 0)
                    {
                        LogFile.WriteLine(LogQu.Dequeue());
                    }
                }
            }
        }

        /// <summary>
        /// [쓰레드] 2초마다 서버 정보를 가져옵니다.
        /// </summary>
        private static void GetServerInfo()
        {
            Stopwatch Ping = new Stopwatch();
            Ping.Start();
            Info info = new Info();
            if (info.GetInfo(Setting.SetIP, 25565)) //열려있을때 서버정보를 저장해놓음
            {
                InPlayer = info.Player_Online + "/" + info.Player_Max;
                Motd = info.Motd;
                
                if (Setting.Player)
                    Player_List = info.Player_LIst;
                Ping.Stop();
                ms = Ping.Elapsed.TotalSeconds;
            }
            else //서버가 닫혀있을경우
            {
                ms = null;
                Motd = "서버가 닫혀있습니다";
                InPlayer = "? / ?";
                Player_List = null;
            }
            Ping.Reset();
        }

        private static void StatusThread()
        {
            while (!Setting.IsExit)
            {
                GetServer = new Thread(new ThreadStart(GetServerInfo));
                GetServer.Start();
                Thread.Sleep(Setting.Status_Update);
                GetServer.Abort();
            }
        }
    }
}
