using System.Web;
using System.Text;
using System.Web.UI;
using System.Data;
using System.Data.OleDb;
using System;

/// <summary>
/// A JavaScript alert
/// </summary>
public static class SES_Common {

    public enum ArrayItemProcessType : long { Delete, Replace, ReplaceOrAddition }

    /// <summary>
    /// Shows a client-side JavaScript alert in the browser.
    /// </summary>
    /// <param name="message">The message to appear in the alert.</param>
    public static void Show(string message) {
        // Cleans the message to allow single quotation marks
        string cleanMessage = message.Replace("'", "\\'").Replace("\r\n", "\\r\\n");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";

        // Gets the executing web page
        Page page = HttpContext.Current.CurrentHandler as Page;

        // Checks if the handler is a Page and that the script isn't allready on the Page
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
            page.ClientScript.RegisterClientScriptBlock(typeof(SES_Common), "alert", script);
        }
    }

    // 判斷使用者的樹節點權限
    public static bool Authorize(string URL, string UserName) {
        URL = URL.ToUpper().Replace(".ASPX", "");
        string[] arPages = WebAuthorityData.GetPages;
        if (arPages == null) {
            string sCondition = " (Account='Anonymous' and RoleOrUser='Role') " + " or Account='" + UserName + "' ";
            arPages = new WebAuthorityData().Select("Page", sCondition);
        }

        if (arPages != null) {
            for (int i = 0; i < arPages.Length; i++) {
                string sTemp = arPages[i].ToUpper().Replace(".ASPX", "");

                if (sTemp.IndexOf("SEST/DEFAULT") > -1)
                    return true;

                if (sTemp != "" && URL.IndexOf(sTemp) > -1) {
                    return true;
                }
            }
        }

        return false;
    }

    // 取得使用者相對應的組別 ( 以 \r\n 為分隔符號)
    public static string getMatchGroup(string sUsers) {
        string sGroups = "";
        string[] arTempEmployees = null, arTempGroups = null;
        string sTempEmployees = "", sTempCondition = "";
        if (sUsers != "") {
            arTempEmployees = sUsers.Replace("\r", "").Split("\n".ToCharArray());
            for (int i = 0; i < arTempEmployees.Length; i++) {
                if (arTempEmployees[i].Trim() != "")
                    sTempEmployees += ",'" + arTempEmployees[i].Trim() + "'";
            }

            if (sTempEmployees != "") {
                sTempCondition = "Name in (" + sTempEmployees.Substring(1) + ")";
                arTempGroups = new HR_DepartmentsData().SelectGroupIDByEmployeeID(sTempCondition);
                for (int i = 0; i < arTempGroups.Length; i++) {
                    sGroups += "\r\n" + arTempGroups[i];
                }
                if (sGroups != "")
                    sGroups = sGroups.Substring(2);
            }
        }

        return sGroups;
    }

    // 取得使用者相對應的 EMail ( 以 ; 為分隔符號)
    public static string getMatchMail(string sUsers) {
        string sEMails = "";
        string[] arTempEmployees = null;
        string sTempEmployees = "", sTempCondition = "";
        if (sUsers != "") {
            arTempEmployees = sUsers.Replace("\r", "").Split("\n".ToCharArray());
            for (int i = 0; i < arTempEmployees.Length; i++) {
                if (arTempEmployees[i].Trim() != "")
                    sTempEmployees += ",'" + arTempEmployees[i].Trim() + "'";
            }

            if (sTempEmployees != "") {
                sTempCondition = "Name in (" + sTempEmployees.Substring(1) + ")";
                DataTable dt = new HR_EmployeesData().SelectIncludeLeave("EMail",sTempCondition);
                for (int i = 0; i < dt.Rows.Count; i++) {
                    sEMails += ";" + dt.Rows[i]["EMail"].ToString();
                }
                if (sEMails != "")
                    sEMails = sEMails.Substring(1);
            }
        }

        return sEMails;
    }


    public static string[] ArrayItemProcess(string[] ar, string FindLikeString, string ReplaceString, ArrayItemProcessType aipt) {
        // ~~~~~~~~~~~~~~~~~~~~~~~~~~ 取代 or 找到取代,找不到新增 ~~~~~~~~~~~~~~~~~~~~~~~
        if (aipt == ArrayItemProcessType.Replace || aipt == ArrayItemProcessType.ReplaceOrAddition) {
            bool bHadReplace = false;
            for (int i = ar.GetLowerBound(0); i < ar.Length; i++) {
                if (ar[i].IndexOf(FindLikeString) > -1) {
                    ar[i] = ReplaceString;
                    bHadReplace = true;
                    break;
                }
            }
            //找不到可以 replace 時, 新增至最後一位
            if (!bHadReplace && aipt == ArrayItemProcessType.ReplaceOrAddition) {
                string[] arTmp = new string[ar.Length + 1];
                ar.CopyTo(arTmp, 0);
                arTmp[ar.Length] = ReplaceString; //插入最後一個位置
                return arTmp;
            }

            return ar;
        }
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


        // ~~~~~~~~~~~~~~~~~~~~~~~~~~ 找到則刪除 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        int iAdd = 0;
        string[] arResult = null;
        if (aipt == ArrayItemProcessType.Delete) {
            arResult = new string[ar.Length - 1];
            for (int i = ar.GetLowerBound(0); i < ar.Length; i++) {
                if (ar[i].IndexOf(FindLikeString) > -1) {
                    iAdd--;
                }
                else {
                    arResult[i + iAdd] = ar[i];
                }
            }
        }
        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

        return arResult;
    }


    // page 返回的共用函數
    public static string BackScript(string ReloadPage, int BackCount) {
        string sScript = "";
        sScript = "<script language='javascript' type='text/javascript'>\r\n";
        sScript += "window.history.go(" + BackCount.ToString() + ");";
        sScript += "window.location.replace('" + ReloadPage + "');";
        sScript += "</script>\r\n";

        return sScript;
    }
    public static string BackScript(int BackCount) {
        string sScript = "";
        sScript = "<script language='javascript' type='text/javascript'>\r\n";
        sScript += "window.history.go(" + BackCount.ToString() + ");";
        sScript += "</script>\r\n";

        return sScript;
    }

    // parse 週付款的格式並傳回 DataTable
    public static DataTable parseExcelFile(string FilePath, string SheetName) {
        /*
        如果Excel中的第一列為欄名,則寫成
        string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\temp\\book1.xls;Extended Properties=\"Excel 8.0;HDR=YES\"";
        */
        //string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=d:\\temp\\book1.xls;Extended Properties=\"Excel 8.0;HDR=NO\"";
        if (!System.IO.File.Exists(FilePath))
            throw new Exception("File not existed");

        OleDbConnection cn = new OleDbConnection();
        DataTable dt = new DataTable();
        try {
            string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + FilePath + ";Extended Properties=\"Excel 8.0;HDR=YES\"";
            cn.ConnectionString = sConnectionString;
            cn.Open();

            if (!SheetName.EndsWith("$"))
                SheetName += "$";
            string sSQL = "SELECT * FROM [" + SheetName + "]";
            //OleDbCommand cmd = cn.CreateCommand();
            //cmd.CommandText = sSQL;
            //OleDbDataReader DR = cmd .ExecuteReader();
            //while (DR.Read()) {
            //    //Console.WriteLine(DR[0].ToString());
            //}

            OleDbDataAdapter adp = new OleDbDataAdapter(sSQL, cn);
            adp.Fill(dt);
            return dt;
        }
        catch (Exception ex) {
            throw ex;
        }
        finally {
            cn.Close();
        }

    }


    // 新增 Work schedule and add to white board
    public static int saveScheduleAndWhiteBoard(string WorkID, string ExpectStartDate, string ExpectEndDate, string Responsibility, string GroupName, string WhiteBoardContents) {
        TEC_MainWorkSchedulesData schedule = new TEC_MainWorkSchedulesData();
        int iScheduleID = 0;

        DateTime dtStart, dtEnd;
        // 確認時間格式
        try {
            if (ExpectStartDate.Trim() != "" && ExpectEndDate.Trim() != "") {
                dtStart = DateTime.Parse(ExpectStartDate.Trim());
                dtEnd = DateTime.Parse(ExpectEndDate.Trim());
            }
            else {
                dtStart = DateTime.MinValue;    // 沒有輸入時間時預設為最小時間
                dtEnd = dtStart;                // 
            }
        }
        catch {
            throw new Exception("Invalid DateTime Format");
        }
        // 確認時間開始與結束時間
        if (dtStart > dtEnd) {
            throw new Exception("Invalid DateTime (Start Date > End Date)");
        }
        //// 確認時間是否有重疊
        //if (dtStart > DateTime.MinValue) {
        //    if (!schedule.CheckValidSchedule(WorkID, ExpectStartDate, ExpectEndDate)) {
        //        throw new Exception("The period is repetition");
        //    }
        //}

        // 新增 schedule
        if (ExpectStartDate == "" || ExpectEndDate == "")
            iScheduleID = schedule.Insert2(WorkID, null, null, Responsibility, GroupName);
        else
            iScheduleID = schedule.Insert2(WorkID, ExpectStartDate, ExpectEndDate, Responsibility, GroupName);

        //新增至白板
        if (dtStart > DateTime.MinValue ) {  // 有輸入日期和時間
            DateTime dtCurrentProcess = dtStart;
            TEC_WhiteBoardData whiteboard = new TEC_WhiteBoardData();
            while (dtCurrentProcess <= dtEnd) {
                whiteboard.Insert(dtCurrentProcess.Year, dtCurrentProcess.Month, dtCurrentProcess.Day, WhiteBoardContents);
                dtCurrentProcess = dtCurrentProcess.AddDays(1);
            }
        }

        return iScheduleID;
    }
    public static int saveScheduleAndWhiteBoard2(string WorkID, string ExpectStartDate, string ExpectEndDate, string Responsibility, string GroupName, string WhiteBoardContents) {
        TEC_MainWorkSchedulesData schedule = new TEC_MainWorkSchedulesData();
        int iScheduleID = 0;

        DateTime dtStart, dtEnd;
        // 確認時間格式
        try {
            if (ExpectStartDate.Trim() != "" && ExpectEndDate.Trim() != "") {
                dtStart = DateTime.Parse(ExpectStartDate.Trim());
                dtEnd = DateTime.Parse(ExpectEndDate.Trim());
            }
            else {
                dtStart = DateTime.MinValue;    // 沒有輸入時間時預設為最小時間
                dtEnd = dtStart;                // 
            }
        }
        catch {
            throw new Exception("Invalid DateTime Format");
        }
        // 確認時間開始與結束時間
        if (dtStart > dtEnd) {
            throw new Exception("Invalid DateTime (Start Date > End Date)");
        }
        // 確認時間是否有重疊
        if (dtStart > DateTime.MinValue) {
            if (!schedule.CheckValidSchedule(WorkID, ExpectStartDate, ExpectEndDate)) {
                throw new Exception("The period is repetition");
            }
        }

        // 新增 schedule
        if (ExpectStartDate == "" || ExpectEndDate == "")
            iScheduleID = schedule.Insert(WorkID, null, null, Responsibility, GroupName);
        else
            iScheduleID = schedule.Insert(WorkID, ExpectStartDate, ExpectEndDate, Responsibility, GroupName);

        //新增至白板
        if (dtStart > DateTime.MinValue) {  // 有輸入日期和時間
            DateTime dtCurrentProcess = dtStart;
            TEC_WhiteBoardData whiteboard = new TEC_WhiteBoardData();
            while (dtCurrentProcess <= dtEnd) {
                whiteboard.Insert(dtCurrentProcess.Year, dtCurrentProcess.Month, dtCurrentProcess.Day, WhiteBoardContents);
                dtCurrentProcess = dtCurrentProcess.AddDays(1);
            }
        }

        return iScheduleID;
    }


    public static void saveFilesStorage(string PageName, string PageKeys, string FileName, string PhysicalPath, string URLPath,
        string ExpireDate, bool delBeforeSave) {

        // 刪除舊的項目
        if (delBeforeSave) {
            Common_FilesStorageData dbFilesStorage = new Common_FilesStorageData();
            DataTable dtFilesStorage = dbFilesStorage.Select(PageName, PageKeys, FileName);
            if (dtFilesStorage.Rows.Count == 1) { // 找到舊有項目
                System.IO.File.Delete(dtFilesStorage.Rows[0]["PhysicalPath"].ToString());       // 刪除檔案
                dbFilesStorage.Delete(dtFilesStorage.Rows[0]["FilesStorageID"].ToString());     // 刪除記錄
            }
        }


        // 新增

    }


    // 轉換 URL 的特殊字元
    public static string ReplaceURLString(string SourceString, bool ReplaceQuestionMark, bool ReplaceAndMark, bool ReplaceEqual) {
        string sRtn = SourceString.Replace("+","%2B").Replace(" ","%20").Replace("/","%2F").Replace("%","%25").Replace("#","%23");
        if ( ReplaceQuestionMark)
            sRtn = sRtn.Replace("?","%3F");
        if (ReplaceAndMark)
            sRtn = sRtn.Replace("&", "%26");
        if (ReplaceEqual)
            sRtn = sRtn.Replace("=", "%3D");

        return sRtn;
    }


}


