using Microsoft.Win32;
using ryCommonDb;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace 开发辅助工具.Manager
{
    public partial class FrmSetting : Form
    {
        public FrmSetting()
        {
            InitializeComponent();
        }

        private void BtnChapeBasePath_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = TxtCshapeBasePath.Text;
            if (folderBrowserDialog1.ShowDialog()==DialogResult.OK)
            {
                TxtCshapeBasePath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            if(ChkAss_Ryp.Checked)
            {
                SetFileAssociation(".ryp", "ryUSQ", "用睿元开发助手打开", Application.ExecutablePath);
            }
            else { DelFileAssociation(".ryp", "ryUSQ"); }
            if(ChkAss_Folder.Checked)
            {
                SetFileAssociation("folder", "ryUSQ", "用睿元开发助手打开", Application.ExecutablePath);
            }
            else { DelFileAssociation("folder", "ryUSQ"); }
            ryCommon.Storage mStor = new ryCommon.Storage();
            mStor.SelectNodeBySet();
            mStor.SetAttrValue("CshapeBasePath", TxtCshapeBasePath.Text);
            mStor.SetAttrValue("ReferenceDll", TxtReferenceDll.Text);
            mStor.SetAttrValue("ReactorPath", TxtReactorPath.Text);
            mStor.SetAttrValue("WinRARPath", TxtWinRARPath.Text);
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                RyQuickSQL mySQL = new RyQuickSQL("Settings");
                mySQL.AddField("name","Setting");
                mySQL.AddField("value", mStor.XMLText);
                if(db.ExecuteNonQuery(mySQL.GetUpdateSQL()+ " where name='Setting'",mySQL)==0)
                {
                    db.ExecuteNonQuery(mySQL.GetInsertSQL(),mySQL);
                }
            }
            db.Free();
            DialogResult = DialogResult.OK;
        }
        /// <summary>
        /// 设置文件关联
        /// </summary>
        /// <returns></returns>
        public bool SetFileAssociation(string ExtName, string sName, string AssDes,string filePath)
        {
            try
            {
                RegistryKey LRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot,RegistryView.Registry32);
                RegistryKey softwareRun = LRoot.OpenSubKey(ExtName + @"\shell\"+sName, true);
                if (softwareRun == null) { softwareRun = LRoot.CreateSubKey(ExtName + @"\shell\" + sName); }
                softwareRun.SetValue("", AssDes, RegistryValueKind.String);
                var Command= softwareRun.OpenSubKey("command",true);
                if (Command == null) { Command = softwareRun.CreateSubKey("command"); }
                Command.SetValue("","\""+ filePath+"\" open \"%1\"");
                Command.Close();
                softwareRun.Close();
                LRoot.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 判断文件关联是否存在
        /// </summary>
        /// <param name="ExtName"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public bool GetFileAssociation(string ExtName, string sName)
        {
            try
            {
                var result = false;
                RegistryKey LRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32);
                RegistryKey softwareRun = LRoot.OpenSubKey(ExtName + @"\shell\"+sName, false);
                if (softwareRun != null)
                {
                    softwareRun.Close();
                    result = true;
                }
                LRoot.Close();
                return result;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 删除文件关联
        /// </summary>
        /// <param name="ExtName"></param>
        /// <param name="sName"></param>
        /// <returns></returns>
        public bool DelFileAssociation(string ExtName, string sName)
        {
            try
            {
                RegistryKey LRoot = RegistryKey.OpenBaseKey(RegistryHive.ClassesRoot, RegistryView.Registry32);
                RegistryKey softwareRun = LRoot.OpenSubKey(ExtName + @"\shell", false);
                if(softwareRun!=null)
                {
                    var shell_name = softwareRun.OpenSubKey(sName,false);
                    if(shell_name!=null)
                    {
                        shell_name.Close();
                        softwareRun.DeleteSubKeyTree(sName);
                    }
                    softwareRun.Close();
                }
                LRoot.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        private void FrmSetting_Load(object sender, EventArgs e)
        {
            ChkAss_Ryp.Checked = GetFileAssociation(".ryp", "ryUSQ");
            ChkAss_Folder.Checked = GetFileAssociation("folder", "ryUSQ");
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                var ds = db.ReadData("select * from Settings where name='Setting'");
                if(mydb.HaveData(ds))
                {
                    var row = mydb.GetData(ds);
                    ryCommon.Storage mStor = new ryCommon.Storage(row["value"].ToString());
                    mStor.SelectNodeBySet();
                    TxtCshapeBasePath.Text = mStor.GetAttrValue("CshapeBasePath");
                    TxtReferenceDll.Text = mStor.GetAttrValue("ReferenceDll");
                    TxtReactorPath.Text = mStor.GetAttrValue("ReactorPath");
                    TxtWinRARPath.Text = mStor.GetAttrValue("WinRARPath");
                    if(TxtWinRARPath.Text=="")
                    {
                        if(System.IO.File.Exists(@"C:\Program Files\WinRAR\WinRAR.exe"))
                        {
                            TxtWinRARPath.Text = @"C:\Program Files\WinRAR\WinRAR.exe";
                        }
                    }
                }
            }
            db.Free();
            LoadVarData();
        }
        private void LoadVarData()
        {
            #region 重新载入数据
            tableModel1.Rows.Clear();
            tableModel1.Selections.Clear();
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                DataSet ds = db.ReadData("select * from VarInfo");
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    DataRow row = ds.Tables[0].Rows[i];
                    XPTable.Models.Row itemList = new XPTable.Models.Row()
                    {
                        Tag = row["id"].ToString()
                    };
                    //需要修改此处
                    itemList.Cells.Add(new XPTable.Models.Cell(row["VarName"].ToString()));//示例
                    itemList.Cells.Add(new XPTable.Models.Cell(row["VarValue"].ToString()));
                    itemList.Cells.Add(new XPTable.Models.Cell(row["Des"].ToString()));
                    tableModel1.Rows.Add(itemList);
                }
            }
            db.Free();
            #endregion
        }
        private void BtnReactorPath_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = TxtReactorPath.Text;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                TxtReactorPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void BtnWinRARPath_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = TxtWinRARPath.Text;
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                TxtWinRARPath.Text = folderBrowserDialog1.SelectedPath;
            }
        }
        private void GetVarRow(string id, int index)
        {
            #region 重新载入数据
            DataProvider mydb = new DataProvider();
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                DataSet ds = db.ReadData("select * from VarInfo where id=" + id);
                if (mydb.HaveData(ds))
                {
                    DataRow row = ds.Tables[0].Rows[0];
                    XPTable.Models.Row itemList = tableModel1.Rows[index];
                    //需要修改此处
                    itemList.Cells[ColVariable.Index].Text = row["VarName"].ToString();
                    itemList.Cells[ColPath.Index].Text = row["VarValue"].ToString();
                    itemList.Cells[ColDes.Index].Text = row["Des"].ToString();
                }
            }
            db.Free();
            #endregion
        }
        private void 新增变量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SuperDesign.Manager.FrmAddVar frm = new SuperDesign.Manager.FrmAddVar()
            {
                Text = "添加变量",
                Icon = Icon,
                isAdd = 1
            };
            if(frm.ShowDialog()==DialogResult.OK)
            {
                #region 获取最后一条记录
                DataProvider mydb = new DataProvider();
                IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
                if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
                {
                    DataSet ds = db.ReadData("select * from VarInfo order by id desc limit 1");
                    for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                    {
                        DataRow row = ds.Tables[0].Rows[i];
                        XPTable.Models.Row itemList = new XPTable.Models.Row()
                        {
                            Tag = row["id"].ToString()
                        };
                        //需要修改此处
                        itemList.Cells.Add(new XPTable.Models.Cell(row["VarName"].ToString()));//示例
                        itemList.Cells.Add(new XPTable.Models.Cell(row["VarValue"].ToString()));
                        itemList.Cells.Add(new XPTable.Models.Cell(row["Des"].ToString()));
                        tableModel1.Rows.Add(itemList);
                    }
                }
                db.Free(); 
                #endregion
            }
            frm.Dispose();
        }

        private void 修改变量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (table1.SelectedItems.Length == 0) { return; }
            string selectId = table1.SelectedItems[0].Tag.ToString();
            int index = table1.SelectedItems[0].Index;
            var frm = new SuperDesign.Manager.FrmAddVar()
            {
                Text = "修改变量",
                Icon = Icon,
                isAdd = 0
            };
            frm.GetInfo(selectId);
            if (frm.ShowDialog() == DialogResult.OK)
            {
                GetVarRow(selectId, index);
            }
            frm.Dispose();
        }

        private void 删除变量ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (table1.SelectedItems.Length == 0) { MessageBox.Show("请先选择要删除的项。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; }
            string selectId = table1.SelectedItems[0].Tag.ToString();
            if (MessageBox.Show("确定要删除该项吗？一旦删除将不可恢复。", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
            {
                return;
            }
            IDbInterface db = Itrycn_Db.CreateDataProvider(Itrycn_Db.dataType);
            if (db.ConnDb(Itrycn_Db.User_SQLConn) == 1)
            {
                db.DelById("VarInfo", selectId);
                tableModel1.Rows.RemoveAt(table1.SelectedItems[0].Index);
            }
        }
    }
}
