using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;
using digioz;

public partial class controls_admin_CategoryManager : System.Web.UI.UserControl
{
    
    protected void Page_Load(object sender, EventArgs e)
    {
        lblMessage.Text = string.Empty;
        lblMessage.Visible = false;
        string lsPattern = @"(?<begin>^.*)(?<query>&VideoId=\d{1,})(?<end>.*$)";
        string lsPicturePattern = @"(?<begin>^.*)(?<query>&PictureId=\d{1,})(?<end>.*$)";
        
        if (!IsPostBack)
        {
            // Handle logic to navigate back to the referring page
            string lsPreviousPage = Request.QueryString["PreviousPage"];
            string lsBackText = string.Empty;
            string lsId = string.Empty;

            if (!string.IsNullOrEmpty(lsPreviousPage))
            {
                //TODO - make sure this is a valid Url, otherwise default to UrlReferer
                this.lnkBack.Visible = true;

                // if we were in the middle of editing a video record,
                // pass its Id to the referring url
                lsId = Request.QueryString["VideoId"];
                if (!string.IsNullOrEmpty(lsId))
                {
                    if (lsPreviousPage.Contains("&VideoId="))
                    {
                        string lsReplace = string.Format("&VideoId={0}",
                                                         lsId);
                        lsPreviousPage = Regex.Replace(lsPreviousPage,
                                                       lsPattern,
                                                       "${begin}" + lsReplace + "${end}");
                    }
                    else
                    {
                        lsPreviousPage = string.Format("{0}&VideoId={1}",
                                                      lsPreviousPage, lsId);
                    }
                }
                else
                {
                    lsId = Request.QueryString["PictureId"];
                    if (!string.IsNullOrEmpty(lsId))
                    {
                        if (lsPreviousPage.Contains("&PictureId="))
                        {
                            string lsReplace = string.Format("&PictureId={0}",
                                                             lsId);
                            lsPreviousPage = Regex.Replace(lsPreviousPage,
                                                           lsPicturePattern,
                                                           "${begin}" + lsReplace + "${end}");
                        }
                        else
                        {
                            lsPreviousPage = string.Format("{0}&PictureId={1}",
                                                          lsPreviousPage, lsId);
                        }
                    }
                }

                this.lnkBack.NavigateUrl = lsPreviousPage;
                lsBackText = Request.QueryString["PreviousTitle"];
                if (!string.IsNullOrEmpty(lsBackText))
                {
                    this.lnkBack.Text = string.Format("Back to {0}", lsBackText);
                }
            }

            this.BindData();

            //Default to Add Category
            CategoryManagerMenu.Items[0].Selected = true;
            this.SetCategoryMode("New");
        }
    }

    /// <summary>
    /// Activate view based on menu item clicked
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void CategoryManagerMenu_MenuItemClick(object sender, MenuEventArgs e)
    {
        CategoryManagerMultiView.ActiveViewIndex =
            Convert.ToInt32(e.Item.Value);

        switch(e.Item.Value)
        {
            case "0":
                this.SetCategoryMode("New");
                break;
            case "1":
                this.BindData();
                break;
        }
    }

    protected void btnNewCategory_Click(object sender, EventArgs e)
    {
        this.SetCategoryMode("New");
    }

    /// <summary>
    /// Save Category to the database
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSaveCategory_Click(object sender, EventArgs e)
    {
        if (CategoryNameReqValidator.IsValid)
        {
            bool lbRetCode;
            string lsError = string.Empty;
            bool lbNewMode = (String.Compare(btnSaveCategory.CommandArgument, "New") == 0);

            CategoryInfo loCategory = new CategoryInfo();
            if (lbNewMode)
            {
                loCategory.ID = -1;
            }
            else
            {
                loCategory.ID = Convert.ToInt32(lblID.Text);
            }

            loCategory.CategoryName = txtCategoryName.Text;
            loCategory.CategoryEntity = ddlEntity.SelectedValue;

            lbRetCode = CategoryInfoManagement.Save(loCategory, 
                                                    out lsError);
            string lsResultMessage;
            
            if (lbRetCode == true)
            {
                lsResultMessage = string.Format("Category {0} successfully",
                                                (lbNewMode) ? "added" : "updated");
                DisplayResult(lblMessage,
                              false,
                              lsResultMessage,
                              lsError);
                if (lbNewMode)
                {
                    txtCategoryName.Text = string.Empty;
                }
            }
            else
            {
                lsResultMessage = string.Format("Failed to {0} category",
                                                (lbNewMode) ? "add" : "update");
                DisplayResult(lblMessage,
                              true,   //Error message
                              lsResultMessage,
                              lsError);
            }

        }
        
    }

    protected void gvCategories_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }

    protected void gvCategories_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }

    protected void gvCategories_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.CommandArgument.ToString()))
        {
            gvCategories.SelectedIndex = Convert.ToInt32(e.CommandArgument);
        }

        if (String.Compare(e.CommandName, "Edit", true) == 0)
        {
            // Display UI for Adding/Editing a Category
            this.SetCategoryMode("Update");
        }
        else if (String.Compare(e.CommandName, "Delete", true) == 0)
        {
            bool lbRetCode = false;
            string lsError = string.Empty;
            int id = Convert.ToInt32(gvCategories.SelectedValue);

            lbRetCode = CategoryInfoManagement.Delete(id, out lsError);
                
            // Reset category list after deleting
            this.BindData();
            
            if (lbRetCode == true)
            {
                DisplayResult(lblMessage,
                              false,
                             "Category deleted successfully");
            }
            else
            {
                DisplayResult(lblMessage,
                              true,
                              "Failed to delete category",
                              lsError);
            }
        }

    }

    private void BindData()
    {
        CategoryInfoList loCategoryList = CategoryInfoManagement.GetCategoriesList();
        gvCategories.DataSource = loCategoryList;
        gvCategories.DataBind();
    }

    /// <summary>
    /// Put "form" in either "Add" or "Edit" mode
    /// </summary>
    /// <param name="psMode"></param>
    private void SetCategoryMode(string psMode)
    {
        if (SetCategoryDetails(psMode))
        {
            // Activate the "Add/Update" view
            CategoryManagerMultiView.ActiveViewIndex = 0;
            btnSaveCategory.CommandArgument = psMode;
        }
    }


    /// <summary>
    /// Initialize controls for adding/editing a category
    /// </summary>
    private bool SetCategoryDetails(string psMode)
    {
        bool lbRetValue = true;
        if (string.Compare(psMode, "Update", true) == 0)
        {
            CategoryInfo loCategory =
                CategoryInfoManagement.GetCategory(Convert.ToInt32(gvCategories.SelectedValue));
                    
            if (loCategory != null)
            {
                lblID.Text = loCategory.ID.ToString();
                txtCategoryName.Text = loCategory.CategoryName;
                ddlEntity.SelectedValue = loCategory.CategoryEntity;
            }
            else
            {
                DisplayResult(lblMessage,
                              true,
                             "Error loading category");
                // signal that we failed
                lbRetValue = false;
            }
        }
        else
        {
            lblID.Text = "-1";
            txtCategoryName.Text = string.Empty;
        }

        return lbRetValue;
    }

    
    protected void gvCategories_PageIndexChanging(object sender, 
                                            GridViewPageEventArgs e)
    {
        gvCategories.PageIndex = e.NewPageIndex;
        this.BindData();
    }

    /// <summary>
    /// Display operation result to the user
    /// </summary>
    /// <param name="bErrorMessage"></param>
    /// <param name="psMessage"></param>
    private void DisplayResult(Label poMessageLabel,
                               bool bErrorMessage,
                               string psMessage)
    {
        poMessageLabel.Visible = true;
        poMessageLabel.Text = psMessage;

        // Success
        if (!bErrorMessage)
        {
            poMessageLabel.CssClass = "messageOk";
        }
        else
        {
            poMessageLabel.CssClass = "messageError";
        }
    }


    /// <summary>
    /// Display operation result to the user.
    /// Also display Error from Database if user is admin.
    /// </summary>
    /// <param name="bErrorMessage"></param>
    /// <param name="psMessage"></param>
    /// <param name="psDatabaseError"></param>
    private void DisplayResult(Label poMessageLabel,
                               bool bErrorMessage,
                               string psMessage,
                               string psDatabaseError)
    {
        this.DisplayResult(poMessageLabel,
                           bErrorMessage,
                           psMessage);
        if (bErrorMessage)
        {
            if (Session["permission"] != null)
            {
                if (Convert.ToInt16(Session["permission"]) == 3)
                {
                    poMessageLabel.Text += "<br/>" + psDatabaseError;
                }
            }
        }
    }
}
