using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _Default : System.Web.UI.Page {
    //the function code for localization on this page
    protected override void InitializeCulture() {

        //string sEng =Session.Contents["Localization"].ToString();

        //if (Request.Form.Get("ctl00$selLanguage") != null)
        //    sEng = Request.Form.Get("ctl00$selLanguage").ToString();

        //if (sEng != null && sEng != "") {
        //System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(sEng);
        //System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture(sEng);

        ProfileCommon p = (ProfileCommon)this.Context.Profile;

        if (Request.Form.Get("ctl00$selLanguage") != null)
            p.lang = Request.Form.Get("ctl00$selLanguage").ToString();
        if (p.lang == String.Empty)
            p.lang = Session["Localization"].ToString();

        if (p.lang.Length > 0) {
            this.Culture = p.lang;
            this.UICulture = System.Globalization.CultureInfo.CreateSpecificCulture(p.lang).Name;
        }
    }
    //select theme
    protected void Page_PreInit(object sender, EventArgs e) {
        Page.Theme = Profile.UI.Theme;
    }

    //protected void LoginButton_Click(object sender, EventArgs e) {
    //    if (Membership.ValidateUser(Login1.UserName, Login1.Password)) {
    //        FormsAuthentication.RedirectFromLoginPage(Login1.UserName, false);
    //    }
    //}

    ////// Login1_LoggedIn 時尚未寫入至 Profile.UserName ,所以在導至 @"Personal\PersonalHome.aspx"
    ////// 時會權限不足, 這裡利用 bIsLogged 當作解決方法
    ////private bool bIsLogged = false; 
    protected void Login1_PreRender(object sender, EventArgs e) {
        //////if (bIsLogged )
        //////    Response.Redirect(@"Personal\PersonalHome.aspx");
    }
    protected void Login1_LoggedIn(object sender, EventArgs e) {
        ////bIsLogged = true;
        Response.Redirect(@"Personal\PersonalHome.aspx");
    }


    string sUserName = "";
    protected void Page_Load(object sender, EventArgs e)  {
        //if (Profile.UserName != "" && Profile.UserName.Length < 15)
        //    Login1.Visible = false;


        ////////////// Announcement //////////////////////////////////////////
        DataTable dtUser = new HR_EmployeesData().SelectExcludeLeave("Name", "Account='" + Profile.UserName + "'");
        if ( dtUser.Rows.Count == 1 )
            sUserName = dtUser.Rows[0]["Name"].ToString();
        else
            Response.Redirect("login.aspx");


        // //預設顯示
        //if (!IsPostBack) {
        //    //txtStartDate.Text = DateTime.Today.AddMonths(-6).ToString("yyyy/MM/dd");
        //    //txtEndDate.Text = DateTime.Today.ToString("yyyy/MM/dd");

        //    //DataTable dt = new Common_AnnouncementData().Select(DateTime.Today);
        //    //ShowAnnouncement(dt);
        //}
        //else {
        //    if (Request[hidDeleteAnnouncementID.ClientID] != null) {
        //        string sAnnoumcementID = Request[hidDeleteAnnouncementID.ClientID].ToString();
        //        new Common_FilesStorageData().Delete("Announcement", sAnnoumcementID);
        //        new Common_AnnouncementData().Delete(sAnnoumcementID);
        //    }
        //}

        // 如果在 IsPostBack 內則動態加入的按鈕沒有辦法trigger event
        DataTable dt;
        if ( !IsPostBack)
            dt = new Common_AnnouncementData().Select(DateTime.Today);
        else{
            dt= btnToSelectClick();
        }
        ShowAnnouncement(dt);
    }
    protected void btnToSelect_Click(object sender, EventArgs e) {
    }
    protected DataTable btnToSelectClick() {
        string sPostFrom = "", sWriter = "", sStartDate = "", sEndDate = "";
        sPostFrom = ddlPostFrom.SelectedValue;
        sWriter = txtWriter.Text;

        try {
            sStartDate = DateTime.Parse(txtStartDate.Text).ToString("yyyy/MM/dd");
            sEndDate = DateTime.Parse(txtEndDate.Text).ToString("yyyy/MM/dd");
        }
        catch {
            sStartDate = ""; sEndDate = "";
            txtStartDate.Text = "";
            txtEndDate.Text = "";
        }

        DataTable dt;
        if (sPostFrom == "" && sWriter == "" && sStartDate == "" && sEndDate == "")
            dt = new Common_AnnouncementData().Select(DateTime.Today); // 預設顯示
        else
            dt = new Common_AnnouncementData().Select(sPostFrom, sWriter, sStartDate, sEndDate);// 條件顯示
        //ShowAnnouncement(dt);
        return dt;

    }
    void ShowAnnouncement(DataTable dt) {
        DataTable dtFiles;

        // remove rows of table
        for (int i = TABLE1.Rows.Count - 1; i >= 0; i--) {
            TABLE1.Rows.RemoveAt(i);
        }

        TableRow tr;
        TableCell tc;
        for (int i = 0; i < dt.Rows.Count; i++) {
            string sAnnouncementID = dt.Rows[i]["AnnouncementID"].ToString();

            //HtmlTableRow tr = new HtmlTableRow();
            //HtmlTableCell tc = new HtmlTableCell();
            tr = new TableRow();
            tc = new TableCell();

            if (i % 2 == 0)
                tr.BackColor = System.Drawing.Color.FromArgb(255,255,153);
            else
                tr.BackColor = System.Drawing.Color.FromArgb(153, 255, 255);
            tc.Attributes["Align"] = "Left";
            tr.Attributes["Height"] = "25px";

            Label lbl = new Label();
            HyperLink hl = new HyperLink();
            //設定顏色
            switch (Convert.ToInt16(dt.Rows[i]["Importance"])) {
                case 1:
                    lbl.ForeColor = System.Drawing.Color.Black;
                    hl.ForeColor = System.Drawing.Color.Black;
                    break;
                case 2:
                    lbl.ForeColor = System.Drawing.Color.Blue;
                    hl.ForeColor = System.Drawing.Color.Blue;
                    break;
                case 3:
                    lbl.ForeColor = System.Drawing.Color.Red;
                    hl.ForeColor = System.Drawing.Color.Red;
                    break;
            }

            if (dt.Rows[i]["Contents"].ToString().Trim() == "") {     // show message only
                lbl.Text = "&#8226[" + dt.Rows[i]["PostFrom"].ToString() + "] " + dt.Rows[i]["Subject"].ToString() + " (" + Convert.ToDateTime(dt.Rows[i]["CreateDate"]).ToString("yyMMddhhmm") + ")&nbsp;&nbsp;&nbsp;";
                tc.Controls.Add(lbl);

                // 有附加檔案
                dtFiles = new Common_FilesStorageData().Select("Announcement", sAnnouncementID);
                for (int iFiles = 0; iFiles < dtFiles.Rows.Count; iFiles++) {
                    hl = new HyperLink();
                    hl.ImageUrl = @"~\imanges\more.gif";
                    hl.Text = dtFiles.Rows[iFiles]["FileName"].ToString();
                    hl.NavigateUrl = dtFiles.Rows[iFiles]["PhysicalPath"].ToString().Replace(
                        ConfigurationManager.ConnectionStrings["FilesStoragePath"].ConnectionString,
                        ConfigurationManager.ConnectionStrings["FilesStorageURL"].ConnectionString.Replace("60.251.203.79", Request.Url.DnsSafeHost)).Replace(@"\", "/");
                    tc.Controls.Add(hl);
                }

                //TABLE1.Rows.Add(tr);
            }
            else {
                hl.Text = "&#8226[" + dt.Rows[i]["PostFrom"].ToString() + "] " + dt.Rows[i]["Subject"].ToString().Trim() + " (" +  Convert.ToDateTime(dt.Rows[i]["CreateDate"]).ToString("yyMMddhhmm") + ")";
                hl.NavigateUrl = "/SEST/Common/AnnouncementDetail.aspx?AnnouncementID=" + sAnnouncementID;
                tc.Controls.Add(hl);
                //tr.Cells.Add(tc);

                // 附加檔案在子網頁顯示
            }

            //Delete button
            Button btnDelete;
            if (dt.Rows[i]["Creator"].ToString() == sUserName) {
                btnDelete = new Button();
                btnDelete.Click += new EventHandler(this.Delete_Clicked);
                btnDelete.Text = Resources.Universal.Data_Delete;
                btnDelete.ToolTip = sAnnouncementID;    // 儲存預刪除的公告ID
                tc.Controls.Add(btnDelete);
            } 

            tr.Cells.Add(tc);
            TABLE1.Rows.Add(tr);
        }
    }

    protected void Delete_Clicked(object sender, EventArgs e) {
        Button btn = (Button)sender;

        string sAnnoumcementID;
        sAnnoumcementID = btn.ToolTip;// Request[hidDeleteAnnouncementID.ClientID].ToString();
        new Common_FilesStorageData().Delete("Announcement", sAnnoumcementID);
        new Common_AnnouncementData().Delete(sAnnoumcementID);

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
    }
    protected void ddlPostFrom_DataBound(object sender, EventArgs e) {
        ((DropDownList)sender).Items.Insert(0, new ListItem("", "", true));
    }
}
