using ryCommon;
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;
using System.Xml;
using 开发辅助工具.Manager;

namespace 开发辅助工具.Tools
{
    public partial class FrmCreateProject : Form
    {
        public FrmCreateProject()
        {
            ProcUse = true;
            InitializeComponent();
            CbbLang.SelectedIndex = 0;
        }
        bool ProcUse = false;
        RyProject project = new RyProject();
        private void FrmCreateProject_Load(object sender, EventArgs e)
        {
            ryCommon.RyFiles.AddDropDrag(TxtFolder.Handle).ElevatedDragDrop += FrmCreateProject_ElevatedDragDrop;
            project.CopyDllToBin = true;
            var lines = RyFiles.ReadAllLines(Application.StartupPath+"\\SysDb\\Folder.txt");
            for (int i = 0; i < lines.Length; i++)
            {
                var item = lines[i].Split('|');
                if(item.Length>=2)
                {
                    if (System.IO.Directory.Exists(item[1]))
                    { AddItem(item[0], item[1]); }
                }
            }           
        }
        private void AddItem(string name,string path)
        {
            XPTable.Models.Row itemList = new XPTable.Models.Row()
            {
                Tag = ""
            };
            //需要修改此处
            itemList.Cells.Add(new XPTable.Models.Cell(name));//示例
            var cell = new XPTable.Models.Cell(path);
            cell.ForeColor = Color.Gray;
            itemList.Cells.Add(cell);
            tableModel1.Rows.Add(itemList);
        }
        private void FrmCreateProject_ElevatedDragDrop(object sender, ElevatedDragDropArgs e)
        {
            TxtFolder.Text = e.Files[0];
            table1.Visible = false;
        }

        private void BtnBrowser_Click(object sender, EventArgs e)
        {
            if(folderBrowserDialog1.ShowDialog()==DialogResult.OK)
            {
                TxtFolder.Text = folderBrowserDialog1.SelectedPath;
                table1.Visible = false;
            }
        }

        private void BtnCreate_Click(object sender, EventArgs e)
        {
            var CshapeBasePath = project.CshapeBasePath;
            var ReferenceDllPath = project.ReferenceDllPath;
            var path = TxtFolder.Text.TrimEnd('\\');
            var project_name = TxtProjectName.Text;
            var project_Eng_name = TxtProjectEngName.Text;
            #region 判断项目是否符合标准
            if (!ryCommon.RyFiles.IsValidFileName(project_name))
            {
                MessageBox.Show("无效的项目名称(中文)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return;
            }
            if (!ryCommon.RyFiles.IsValidFileName(project_Eng_name) || !project_Eng_name.Replace(" ", "").IsEngOrNum())
            {
                MessageBox.Show("无效的项目名称(英文)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return;
            }
            else if (project_Eng_name.Length < 3 || project_Eng_name.Substring(0, 1).IsInt() || project_Eng_name.Substring(0, 1) == " ")
            {
                MessageBox.Show("无效的项目名称(英文)", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return;
            } 
            var full_path = path + "\\" + project_name;
            if(System.IO.Directory.Exists(path + "\\Bin") && System.IO.Directory.Exists(path + "\\Source"))
            {
                full_path = path;
            }
            ryCommon.RyFiles.CreateDirectory(full_path);
            if(!System.IO.Directory.Exists(full_path))
            {
                MessageBox.Show("创建路径失败。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);return;
            }
            #endregion
            BtnCreate.Enabled = false;
            var prog_lang = "c#";
            if (CbbLang.SelectedIndex == 0) { prog_lang = "c#"; }
            else if (CbbLang.SelectedIndex == 1) { prog_lang = "delphi"; }
            #region 创建项目必备文件夹和文件
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Bin\\Debug\\"+project_Eng_name);
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Source");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Res");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Res\\ThirdParty");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Res\\Images");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\Green");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\Green\\HistoryVer");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\Install");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\Install\\HistoryVer");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\OriginalFiles");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Publish\\UpdateFile");
            ryCommon.RyFiles.CreateDirectory(full_path + "\\Help");
            if (!System.IO.File.Exists(full_path + "\\CHANGELOG.md"))
            { ryCommon.RyFiles.WriteAllText(full_path + "\\CHANGELOG.md", "", Encoding.UTF8); }
            if (!System.IO.File.Exists(full_path + "\\README.md"))
            { ryCommon.RyFiles.WriteAllText(full_path + "\\README.md", "# "+ project_name+ "\r\n\r\n#### 介绍\r\n", Encoding.UTF8); }
            if (!System.IO.File.Exists(full_path + "\\Publish\\Publish.set"))
            {
                ryCommon.RyFiles.WriteAllText(full_path + "\\Publish\\Publish.set", "#del表示删除文件;copy表示复制文件;" +
               "\r\n#原目录:Bin\\Debug\\或Bin\\Release,目标目录:Publish\\OriginalFiles" +
               "\r\ndel:UserDb\r\ndel:Db\r\ncopy:SysDb\\*->SysDb\\", Encoding.UTF8);
            }
            #endregion
            if (prog_lang == "c#")
            {
                #region 生成混淆信息
                ReactorXML xml = new ReactorXML();
                xml.LoadXML(Application.StartupPath + "\\SysDb\\混淆.nrproj");
                if (!System.IO.File.Exists(full_path + "\\Bin\\混淆_Debug.nrproj"))
                {
                    List<string> files_debug = new List<string>
                    {
                    "Debug\\"+project_Eng_name+"\\" + project_Eng_name + ".exe",
                    "Debug\\"+project_Eng_name+"\\" + "MyDb.dll",
                    "Debug\\"+project_Eng_name+"\\" + "MyDb_SQLite.dll",
                    "Debug\\"+project_Eng_name+"\\" + "ryUpdate.dll",
                    "Debug\\"+project_Eng_name+"\\" + "ryControls.dll"
                    };
                    xml.Save(full_path + "\\Bin\\混淆_Debug.nrproj", files_debug);
                }
                if (!System.IO.File.Exists(full_path + "\\Bin\\混淆_Release.nrproj"))
                {
                    List<string> files_Release = new List<string>
                    {
                    "Release\\"+project_Eng_name+"\\" + project_Eng_name + ".exe",
                    "Release\\"+project_Eng_name+"\\" + "MyDb.dll",
                    "Release\\"+project_Eng_name+"\\" + "MyDb_SQLite.dll",
                    "Release\\"+project_Eng_name+"\\" + "ryUpdate.dll",
                    "Release\\"+project_Eng_name+"\\" + "ryControls.dll"
                     };
                    xml.Save(full_path + "\\Bin\\混淆_Release.nrproj", files_Release);
                }
                #endregion
            }
            #region 设置项目配置文件
            ryCommon.Ini ini = new ryCommon.Ini(full_path + "\\查看项目.ryp");
            ini.WriteIni("project", "name", project_name);//项目名称
            ini.WriteIni("project", "engname", project_Eng_name);//英文项目名称
            ini.WriteIni("project", "usqver", 3);//使用的标准版本,新毕方项目标准基于USQ 3
            ini.WriteIni("project", "proglang", prog_lang);//项目使用的语言
            var guid = ini.ReadIni("project", "progID", Guid.NewGuid().ToString("D"));
            ini.WriteIni("project", "progID", guid);//项目唯一ID,用于区分不同项目

            if (!System.IO.File.Exists(full_path + "\\.gitignore")) //复制git忽略规则
            {
                RyFiles.CopyBigFile(Application.StartupPath+ "\\SysDb\\.gitignore", full_path + "\\.gitignore");
            }
            #endregion
            if (!ChkUnCreateProject.Checked)
            {
                #region 复制和修改基准项目
                if (System.IO.Directory.Exists(CshapeBasePath) && prog_lang == "c#") //存在基准项目
                {
                    ryCommon.RyFiles.DeleteFile(full_path + "\\Bin\\Debug\\CommonControls");
                    var source_folder = full_path + "\\Source\\" + project_Eng_name;
                    ryCommon.RyFiles.CopyFileOrFolder(CshapeBasePath, source_folder);
                    ryCommon.RyFiles.DeleteFile(source_folder + "\\Bin");
                    ryCommon.RyFiles.DeleteFile(source_folder + "\\obj");
                    if (System.IO.File.Exists(source_folder + "\\Itrycn_Project.csproj"))
                    {
                        ryCommon.RyFiles.MoveFile(source_folder + "\\Itrycn_Project.csproj", source_folder + "\\" + project_Eng_name + ".csproj");
                        ryCommon.RyFiles.MoveFile(source_folder + "\\Itrycn_Project.csproj.user", source_folder + "\\" + project_Eng_name + ".csproj.user");
                    }
                    if (System.IO.File.Exists(source_folder + "\\Itrycn_Project2.csproj"))
                    {
                        ryCommon.RyFiles.MoveFile(source_folder + "\\Itrycn_Project2.csproj", source_folder + "\\" + project_Eng_name + ".csproj");
                        ryCommon.RyFiles.MoveFile(source_folder + "\\Itrycn_Project2.csproj.user", source_folder + "\\" + project_Eng_name + ".csproj.user");
                    }
                    #region 写入新的版本信息
                    var AssemblyInfo = ryCommon.RyFiles.ReadAllText(Application.StartupPath + "\\SysDb\\AssemblyInfo.cs");
                    AssemblyInfo = AssemblyInfo.Replace("@AssemblyTitle", project_Eng_name);
                    AssemblyInfo = AssemblyInfo.Replace("@AssemblyProduct", project_Eng_name);
                    AssemblyInfo = AssemblyInfo.Replace("@Copyright", "Copyright 2010-"+DateTime.Now.Year);
                    ryCommon.RyFiles.WriteAllText(source_folder + "\\Properties\\AssemblyInfo.cs", AssemblyInfo, Encoding.UTF8);
                    #endregion
                    #region 替换命名空间
                    //var Resources = ryCommon.RyFiles.ReadAllText(source_folder + "\\Properties\\Resources.Designer.cs");
                    //Resources = Resources.Replace("Itrycn_Project.Properties", project_Eng_name.Replace(" ", "") + ".Properties");
                    //Resources = Resources.Replace("Itrycn_Project2.Properties", project_Eng_name.Replace(" ", "") + ".Properties");
                    //ryCommon.RyFiles.WriteAllText(source_folder + "\\Properties\\Resources.Designer.cs", Resources, Encoding.UTF8);
                    //var frmmain = ryCommon.RyFiles.ReadAllText(source_folder + "\\frmmain.Designer.cs");
                    //frmmain = frmmain.Replace("Itrycn_Project.Properties", project_Eng_name.Replace(" ", "") + ".Properties");
                    //frmmain = frmmain.Replace("Itrycn_Project2.Properties", project_Eng_name.Replace(" ", "") + ".Properties");
                    //ryCommon.RyFiles.WriteAllText(source_folder + "\\frmmain.Designer.cs", frmmain, Encoding.UTF8);
                    #endregion
                    project.SetCSproj(source_folder + "\\" + project_Eng_name + ".csproj", project_Eng_name);
                }
                #endregion
            }
            BtnCreate.Enabled = true;
            MessageBox.Show("创建成功。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            RyFiles.OpenFile(full_path);
        }

        private void TxtFolder_Enter(object sender, EventArgs e)
        {
            if (ProcUse) { return; }
            table1.Location = new Point(TxtFolder.Left,TxtFolder.Top+TxtFolder.Height);
            table1.Visible = true;
            table1.BringToFront();
        }

        private void TxtFolder_Leave(object sender, EventArgs e)
        {
            if (!table1.Focused)
            {
                table1.Visible = false;
            }
        }

        private void table1_Leave(object sender, EventArgs e)
        {
            if (!TxtFolder.Focused)
            {
                table1.Visible = false;
            }
        }

        private void table1_CellLostFocus(object sender, XPTable.Events.CellFocusEventArgs e)
        {
            if (e.Row == -1) { table1.Visible = false; }
        }

        private void TxtFolder_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (table1.Visible)
                {
                    table1.TableModel.Selections.Clear();
                    table1.TableModel.Selections.AddCells(0, 0, 0, columnModel1.Columns.Count - 1);
                    table1.Focus();
                }
            }
        }

        private void table1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Up)
            {
                if (table1.SelectedItems.Length > 0 && table1.SelectedItems[0].Index == 0)
                {
                    table1.TableModel.Selections.Clear();
                    TxtFolder.Select();
                    TxtFolder.SelectionLength = 0;
                    //rySearch1.Select();
                }
            }
            else if (e.KeyCode == Keys.Enter)
            {
                if (table1.SelectedItems.Length > 0)
                {
                    TxtFolder.Text = table1.SelectedItems[0].Cells[ColPath].Text;
                    TxtFolder.SelectionLength = 0;
                    TxtFolder.SelectionStart = 0;
                    table1.Visible = false;
                }
            }
        }

        private void table1_Click(object sender, EventArgs e)
        {
            if (table1.SelectedItems.Length > 0)
            {
                TxtFolder.Text = table1.SelectedItems[0].Cells[ColPath].Text;
                TxtFolder.SelectionLength = 0;
                TxtFolder.SelectionStart = 0;
                table1.Visible = false;
            }
        }

        private void FrmCreateProject_Click(object sender, EventArgs e)
        {
            table1.Visible = false;
        }

        private void FrmCreateProject_Shown(object sender, EventArgs e)
        {
            ProcUse = false;
        }

        private void TxtFolder_Click(object sender, EventArgs e)
        {
            table1.Location = new Point(TxtFolder.Left, TxtFolder.Top + TxtFolder.Height);
            table1.Visible = true;
            table1.BringToFront();
        }
    }
}