using CCWin;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SufeiUtil;
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Windows.Forms;

namespace MOKA_Factory_Tools
{
    public partial class login : Skin_Color
    {
        /// <summary>
        /// G客户NTF功能是否开启;
        /// </summary>
        public bool IsNTF { get; set; } = false;
        public int enable;
        string path = AppDomain.CurrentDomain.BaseDirectory;
        LoginOutput loginOutput1 = new LoginOutput()
        {
            factoryname = "",
            factorynum = ""
        };

        string ErrorDBPath = AppDomain.CurrentDomain.BaseDirectory + "\\Error.db";
        SQLiteConnection ErrorDB = null;
        public login()
        {
            InitializeComponent();
            AccountText.Focus();
            CommonMethod.CreateDirectory(path + "\\download");
            CommonMethod.CreateDirectory(path + "\\Keys");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\CIKEY");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\DeviceID");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\ESN");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\HDCPKEY");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\HDCPKEY22");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\MAC");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\Widevine");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\WiDi");
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\Attestation"); 
            CommonMethod.CreateDirectory(path + "\\Keys\\Demo\\MGK"); 
            if (!File.Exists(ErrorDBPath))
            {
                if (SQLiteHelper.NewDbFile(ErrorDBPath))
                {
                    SQLiteHelper.NewTable(ErrorDBPath, "ErrorReport", "(ID INTEGER PRIMARY KEY AUTOINCREMENT,url varchar,content varvhar,gener_date DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),report_date DATETIME)");
                    SQLiteHelper.NewTable(ErrorDBPath, "CopyDelayReport", "(ID INTEGER PRIMARY KEY AUTOINCREMENT,bid varchar,url varchar,content varvhar,copy_date DATETIME DEFAULT (datetime(CURRENT_TIMESTAMP,'localtime')),report_date DATETIME)");
                    SQLiteHelper.NewTable(ErrorDBPath, "ProductionCount", "(bid varchar,count varchar)");
                }
            }
            if (ErrorDB == null)
            {
                ErrorDB = new SQLiteConnection("data source=" + ErrorDBPath);
                ErrorDB.Open();
            }

            getTestModeInfo();
        }

        private void getTestModeInfo()
        {
            // 读取win.ini或注册表;
            StringBuilder MyString = new StringBuilder(256);
            CommonMethod.GetProfileString("MOKAFactoryTools", "TestMode", "0", MyString, 256);
            if (MyString.ToString().Equals("1"))
            {
                TestMode.testMode = true;
                TestMode.SetTestMode(true);
                // 开启了测试模式;
                CommonMethod.GetProfileString("MOKAFactoryTools", "VirMAC", "B0-00-00-00-00-0B", MyString, 256);
                if (MyString.ToString().Equals("B0-00-00-00-00-0B"))
                {// 惠州工厂;
                    AccountText.Text = "Huizhou";
                    PwdText.Text = "admin";
                }
                else if (MyString.ToString().Equals("A0-00-00-00-00-0A"))
                {// 三华工厂;
                    AccountText.Text = "SanHua";
                    PwdText.Text = "admin";
                }
                else if (MyString.ToString().Equals("C0-00-00-00-00-0C"))
                {// 泰霖工厂;
                    AccountText.Text = "Talent";
                    PwdText.Text = "admin";
                }

                TestMode.MAC = MyString.ToString();

                JObject jObject;
                using (StreamReader file = File.OpenText(LocalPath.localpath + "\\Config.json"))
                {
                    using (JsonTextReader reader = new JsonTextReader(file))
                    {
                        jObject = (JObject)JToken.ReadFrom(reader);
                        reader.Close();
                        jObject["FactoryName"] = AccountText.Text;
                    }
                }
                using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
                {
                    writer.Write(jObject.ToString());
                }
            }
            else
            {
                TestMode.testMode = false;
                TestMode.SetTestMode();
#if DEBUG
                TestMode.MAC = "C4-00-AD-17-61-3D&C4-00-AD-17-61-3C&";
#else
                TestMode.MAC = CommonMethod.GetMacAddress();
#endif
            }
        }

        private void OnBtnLogin(object sender, EventArgs e)
        {
            if (PwdText.Text == "zhangyi" && AccountText.Text == "zhangyi")
                enable = 1;
            else if (PwdText.Text == "offline" && AccountText.Text == "offline")
                enable = 3;
            else if (PwdText.Text.Trim().Length > 0 && AccountText.Text.Trim().Length > 0)
            {
#region G客户NTF功能开启;
                if ( IsNTF )
                {
                    if ( LineText.Text.Length == 0 )
                    {
                        MessageBox.Show("Line should not be empty!");
                        return;
                    }
                }
#endregion

                if (CommonMethod.UserLogin(TestMode.loginUrl, AccountText.Text, PwdText.Text, TestMode.MAC, ErrorDB,out loginOutput1))
                {
                    enable = 0;

                    JObject jObject;
                    using (StreamReader file = File.OpenText(LocalPath.localpath + "\\Config.json"))
                    {
                        using (JsonTextReader reader = new JsonTextReader(file))
                        {
                            jObject = (JObject)JToken.ReadFrom(reader);
                            reader.Close();
                            jObject["FactoryName"] = loginOutput1.factoryname;
                            jObject["FactoryNum"] = loginOutput1.factorynum;
                            jObject["Line"] = LineText.Text;
                        }                     
                    }
                    using (StreamWriter writer = new StreamWriter(LocalPath.localpath + "\\Config.json"))
                    {
                        writer.Write(jObject.ToString());
                    }
                }
                else
                {
                    MessageBox.Show(LResource.LoginFail + "\r\n" + loginOutput1.msg);
                    return;
                }
            }                  
            else
            {               
                enable = 2;
            }

            // 保存登录信息;
            CommonMethod.SaveLoginInfo(AccountText.Text, PwdText.Text);
            CommonMethod.FactoryName = loginOutput1.factoryname;
            UpgradeMsgList upgradeMsgList = new UpgradeMsgList();
            var FactoryNum = loginOutput1.factorynum;
            if(FactoryNum.Length>0)
            {
                try
                {
                    if (CommonMethod.UpgradeCheck(TestMode.upgradeUrl, FactoryNum, ErrorDB, out upgradeMsgList))
                    {
                        if (CommonMethod.CompareVersion(upgradeMsgList.upgrade.version, System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()))
                        {
                            Upgrade upgrade = new Upgrade(ErrorDB, upgradeMsgList.upgrade.fileurl, loginOutput1.factorynum);
                            upgrade.Show();
                        }
                        else
                        {
                            ErrorDB.Close();
                            ErrorDB.Dispose();

                            Main form1 = new Main(enable);
                            form1.Show();
                            this.Hide();
                        }
                    }
                    else
                    {
                        MessageBox.Show(LResource.UpgradeCheckFail);
                        ErrorDB.Close();
                        ErrorDB.Dispose();
                        Main form1 = new Main(enable);
                        form1.Show();
                        this.Hide();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ServicePointManager.SecurityProtocol.ToString());
                    MessageBox.Show(ex.Message);
                    MessageBox.Show(LResource.UpgradeCheckFail);
                    ErrorDB.Close();
                    ErrorDB.Dispose();
                    Main form1 = new Main(enable);
                    form1.Show();
                    this.Hide();
                }
            }
            else
            {
                ErrorDB.Close();
                ErrorDB.Dispose();
                MessageBox.Show(LResource.PleaseLogin);
                Main form1 = new Main(enable);
                form1.Show();
                this.Hide();
            }                    
        }

        
        public string format(uint data,uint length)
        {
            return String.Format("{0:D" + length.ToString() + "}", data);
        }

        private void login_Load(object sender, EventArgs e)
        {
            using (StreamReader file = File.OpenText(LocalPath.localpath + "\\Config.json"))
            {
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    JObject jObject = (JObject)JToken.ReadFrom(reader);
                    reader.Close();
                    AccountText.Text = jObject["FactoryName"] == null ? (!CommonMethod.AddJsonConfig("FactoryName", null) ? "" : "") : jObject["FactoryName"].Value<string>();
                    loginOutput1.factoryname = jObject["FactoryName"] == null ? "" : jObject["FactoryName"].Value<string>();
                    loginOutput1.factorynum=jObject["FactoryNum"] == null ? "" : jObject["FactoryNum"].Value<string>();
                    HttpHelper.Tracert = jObject["Tracert"] == null ? false : jObject["Tracert"].Value<bool>();
#region G客户NTF功能开启;
                    if (jObject["NTF"] != null)
                    {
                        IsNTF = jObject["NTF"].Value<bool>();
                        if (IsNTF)
                        {
                            skinLabel3.Visible = true;
                            LineText.Visible = true;

                            BtnLogin.Location = new System.Drawing.Point(70, 152);
                            BtnLogin.Size = new System.Drawing.Size(90, 33);
                            this.Size = new System.Drawing.Size(230, 200);
                        }

                        if (jObject["Line"] != null)
                        {
                            string Line = jObject["Line"].Value<string>();
                            LineText.Text = Line;
                        }
                    }
#endregion
                }
            }            
            System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName("SCBC Factory Tools");//获取指定的进程名   
            if (myProcesses.Length > 1)
            {
                MessageBox.Show(LResource.AlreadyRun);
                Application.Exit();         
            }

            System.Diagnostics.Process[] myProcesses2 = System.Diagnostics.Process.GetProcessesByName("MOKA Factory Tools");//获取指定的进程名   
            if (myProcesses2.Length > 1)
            {
                MessageBox.Show(LResource.AlreadyRun);
                Application.Exit();
            }
        }

        private void login_KeyDown(object sender, KeyEventArgs e)
        {
            // 判断是否回车登录;
            if (e.KeyCode == Keys.Enter)
            {
                OnBtnLogin(sender, e);
            }
        }

        private void PwdText_KeyDown(object sender, KeyEventArgs e)
        {
            // 判断是否回车登录;
            if (e.KeyCode == Keys.Enter)
            {
                OnBtnLogin(sender, e);
            }
        }

        private void LineText_KeyDown(object sender, KeyEventArgs e)
        {
            // 判断是否回车登录;
            if (e.KeyCode == Keys.Enter)
            {
                OnBtnLogin(sender, e);
            }
        }
    }
}
