using Tiobon.Core.OPS.Tool.OPS.Tool.Helper;
using Tiobon.Core.OPS.Tool.OPS.Tool.Model;
using Tiobon.Core.OPS.Tool.OPS.Tool.src;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.NetworkInformation;
using System.Web.Script.Serialization;

namespace Tiobon.Core.OPS.Tool.OPS.Tool.Src
{
    public class Login_method
    {
        #region 保存配置
        /// <summary>
        /// 保存配置
        /// </summary>
        public void Saveconfig(Config config)
        {
            try
            {
                var config_list = Loadconfig();
                config_list.Add(config);
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                string json = jsonSerializer.Serialize(config_list);
                json = Const.AesEncrypt(json, "12345678876543211234567887654abc");
                File.WriteAllText("Config/config.json", json);
            }
            catch (Exception e)
            {
                MessageBoxEx.Show(e.Message);
            }
        }


        public void Saveconfig(List<Config> config)
        {
            try
            {
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                string json = jsonSerializer.Serialize(config);
                json = Const.AesEncrypt(json, "12345678876543211234567887654abc");
                File.WriteAllText("Config/config.json", json);
            }
            catch (Exception e)
            {
                MessageBoxEx.Show(e.Message);
            }
        }
        #endregion

        public bool TestPing(ref string message)
        {
            using (Ping ping = new Ping())
            {
                try
                {
                    PingReply pingReply = ping.Send(Const.config.ip);
                    if (pingReply.Status == IPStatus.Success)
                    {
                        return true;
                    }

                    else
                    {
                        message = "Ping主机不通或服务器禁Ping，是否检查配置？";
                        return false;
                    }
                }
                catch 
                {
                    message = "Ping主机不通或服务器禁Ping，是否检查配置？";
                    return false;
                }
            }
        }

        #region 测试连接
        public bool Testcon(ref string message)
        {
            try
            {
                SSHHelper sSH = new SSHHelper(Const.config.ip, Const.config.ssh_port, Const.config.ssh_user, Const.config.ssh_passwd);
                if (!sSH.Connect())
                {
                    message = "连接失败，是否检查配置？";
                    return false;
                }
                sSH = new SSHHelper(Const.config.ip, Const.config.ssh_port, "root", Const.config.supasswd);
                SFTPHelper sFTP = new SFTPHelper(Const.config.ip, Const.config.ssh_port, "root", Const.config.supasswd);
                if (message == "again")
                {
                    sSH = new SSHHelper(Const.config.ip, Const.config.ssh_port, Const.config.ssh_user, Const.config.ssh_passwd);
                    sFTP = new SFTPHelper(Const.config.ip, Const.config.ssh_port, Const.config.ssh_user, Const.config.ssh_passwd);
                }

                if (sSH.Connect())
                {
                    sFTP.Connect();
                    sFTP.Put("Config/script.ihdis", "/tmp/", "script.tar");
                    sFTP.Disconnect();
                    if (message == "again")
                    {
                        sSH.Excute_cmd("sudo rm -rf /tmp/ihdis_script \n sudo mkdir /tmp/ihdis_script \n sudo tar xf /tmp/script.tar -C /tmp/ihdis_script/", out _);
                    }
                    else
                    {
                        sSH.Excute_cmd("rm -rf /tmp/ihdis_script \n mkdir /tmp/ihdis_script \n tar xf /tmp/script.tar -C /tmp/ihdis_script/", out _);
                    }
                    Const.Script_path = "/tmp/ihdis_script";
                    Const.config.tmp_dir = $"/home/{Const.config.ssh_user}/ihdis";
                    if (message != "again")
                    {
                        Nopwd();
                    }
                    sSH.Disconnect();
                    return true;
                }
                else
                {
                    if (message == "again")
                    {
                        message = "连接失败";
                    }
                    else
                    {
                        message = "连接失败，是否使用普通用户尝试？";
                    }
                    return false;
                }
            }
            catch (Exception ex)
            {
                message = "连接失败，是否检查配置？";
                Const.write_log(ex.Message);
                return false;
            }
        }
        #endregion

        #region 设置免密
        public void Nopwd()
        {
            SSHHelper sSH = new SSHHelper(Const.config.ip, Const.config.ssh_port, "root", Const.config.supasswd);
            var flag = sSH.Excute_cmd($"sudo sh {Const.Script_path}/script/other/sudo_nopwd.sh {Const.config.ssh_user}", out string result);
            if (!flag)
            {
                string log = $"初始化失败：{result}";
                throw new Exception(log);
            }
        }
        #endregion

        #region 读取配置
        /// <summary>
        /// 读取配置
        /// </summary>
        public List<Config> Loadconfig()
        {
            if (!File.Exists("Config/config.json"))
            {
                return new List<Config>();
            }
            using (StreamReader file = File.OpenText("Config/config.json"))
            {
                string fm = file.ReadToEnd();
                if (string.IsNullOrEmpty(fm))
                {
                    return new List<Config>();
                }
                try
                {
                    fm = Const.AesDecrypt(fm, "12345678876543211234567887654abc");
                }
                catch
                {
                    //兼容未加密的配置文件
                }
                JavaScriptSerializer js = new JavaScriptSerializer();
                List<Config> user = js.Deserialize<List<Config>>(fm);
                return user;
            }
        }
        #endregion
    }
}
