namespace Thousandto.DIY
{
    /// <summary>
    /// 读取UIConfig.xlsx
    /// </summary>
    public class UIConfigExcel
    {
        /// <summary>
        /// 插入到UIConfig表后生成的id
        /// </summary>
        public const string ExcelPath = "../../Gamedata/Config/client/UIConfig.xlsx";

        public static int GetFormIDEx(string formName)
        {
            int id = -1;
            ExcelWorkSheet excel = new ExcelWorkSheet(ExcelPath);
            int rows = excel.GetLength(0);
            int columns = excel.GetLength(1);
            for(int i = 0; i < rows; ++i)
            {
                if(columns >= 2)
                {
                    if (excel.Cells[i, 2] == formName)
                    {
                        int.TryParse(excel.Cells[i, 0], out id);
                        return id;
                    }
                }
            }

            return id;
        } 

        public static bool AddForm(string formName, out int formId, bool isLua = false)
        {
            formId = -1;
            int existId = GetFormIDEx(formName);
            if (existId > 0)
                return false;

            ExcelWorkSheet excel = new ExcelWorkSheet(ExcelPath);
            int rows = excel.GetLength(0);
            int id = -1;

            while (rows > 0)
            {
                if (int.TryParse(excel.Cells[rows - 1, 0], out id))
                {
                    id = id + 1;
                    excel.Cells[rows, 0] = "" + id;
                    excel.Cells[rows, 1] = formName;
                    excel.Cells[rows, 2] = isLua? "UILuaForm" : formName;
                    excel.Save();
                    formId = id;
                    return true;
                }
                --rows;
            }

            return false;
        }
    }
}