using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using digioz;

public partial class controls_admin_ModuleManager : System.Web.UI.UserControl
{
    digioz.BoxItemList coBoxItemList, coBoxItemListLeft, coBoxItemListRight;
    private static UserPermissionList coPermissionList;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            coPermissionList = UserManagement.GetUserPermissions();
            setModuleData();
            setConfigData();
            //set default Mode to "New"
            lblMode.Text = "New";
        }
    }

    // Setup module data
    private void setModuleData()
    {
        // menu data
        updateMenuItemList();

        //Get list of abbrev for drop-down
        tbMenuActionType.DataSource = AbbreviationsManagement.GetAbbrevList("m");
        tbMenuActionType.DataValueField = "abbrv_name";
        tbMenuActionType.DataTextField = "abbrv_desc";
        tbMenuActionType.DataBind();
       
        // box item list
        updateBoxItemList();

        // box action types
        //this.cbBoxActionTypes.DataSource = getBoxActionTypes();
        //this.cbBoxActionTypes.DataBind();

        //Get list of abbrev for drop-down
        cbBoxActionTypes.DataSource = AbbreviationsManagement.GetAbbrevList("b");
        cbBoxActionTypes.DataValueField = "abbrv_name";
        cbBoxActionTypes.DataTextField = "abbrv_desc";
        cbBoxActionTypes.DataBind();

        // parmission list
        this.ddlPermission.DataSource = coPermissionList;
        this.ddlPermission.DataBind();
        this.ddlPermission.Items.Insert(0, new ListItem("Guest User", "-1"));
    }

    private void updateMenuItemList()
    {
        digioz.MenuItemList loMenuItemList = digioz.MenuItemManagement.GetMenuItemList(-1);
        this.lMenuItems.DataSource = loMenuItemList;
        this.lMenuItems.DataBind();
    }

    private void updateBoxItemList()
    {
        coBoxItemList = digioz.BoxItemManagement.GetBoxItemList();
        coBoxItemListLeft = digioz.BoxItemManagement.GetBoxItemListByLocation("L");
        coBoxItemListRight = digioz.BoxItemManagement.GetBoxItemListByLocation("R");

        gridLeftBox.DataSource = coBoxItemListLeft;
        gridLeftBox.DataBind();

        gridRightBox.DataSource = coBoxItemListRight;
        gridRightBox.DataBind();

        this.cbBoxlist.DataSource = coBoxItemList;
        this.cbBoxlist.DataBind();
    }

    internal void setConfigData()
    {
        digioz.ConfigurationList loConfigurationList = digioz.ConfigurationManagement.GetConfigurationList();
        this.gridConfigItems.DataSource = loConfigurationList;
        this.gridConfigItems.DataBind();
    }

    // Set the displayed content in viewEditPage based on selection in list ViewListPage
    // If set psMode to New, then poMenuItem must be null;
    // If set psMode to Update, then poMenuItem must be a valid instance
    private void setMenuDetail(digioz.MenuItem poMenuItem, string psMode)
    {
        this.lblMode.Text = psMode;
        if (poMenuItem != null)
        {
            lblMenuID.Text = poMenuItem.ID.ToString();
            tbMenuName.Text = poMenuItem.Name;
            tbMenuActionData.Text = poMenuItem.ActionData;
            tbMenuActionType.Text = poMenuItem.ActionType;
            try
            {
                cbBoxlist.SelectedValue = Convert.ToString(poMenuItem.BoxID);
            }
            catch
            {
                cbBoxlist.SelectedValue = null;
            }
        }
        else
        {
            lblMenuID.Text = string.Empty;
            tbMenuName.Text = string.Empty;
            tbMenuActionData.Text = string.Empty;
        }
    }

    // Set the displayed content in ViewEditBox
    // If set psMode to New, then poBoxItem must be null;
    // If set psMode to Update, then poBoxItem must be a valid instance
    private void setBoxDetail(digioz.BoxItem poBoxItem, string psMode)
    {
        this.lblMode.Text = psMode;
        if (poBoxItem != null)
        {
            lblBoxID.Text = poBoxItem.ID.ToString();
            tbBoxName.Text = poBoxItem.Name;
            if (poBoxItem.Location == "L")
            {
                rbBoxLocationLeft.Checked = true;
            }
            else
            {
                rbBoxLocationRight.Checked = true;
            }
            cbBoxActionTypes.Text = poBoxItem.ActionType;
            ddlPermission.SelectedValue = poBoxItem.Permission.ToString();
            tbBoxActionData.Text = poBoxItem.ActionData;
        }
        else
        {
            lblBoxID.Text = string.Empty;
            tbBoxName.Text = string.Empty;
            tbBoxActionData.Text = string.Empty;
        }
    }

    // This handles model manager menu selection events
    protected void doOnModuleManagerMenuClick(object sender, MenuEventArgs e)
    {
        int liIndex = Int32.Parse(e.Item.Value);
        this.lblMenuSaveSatus.Visible = false;
        this.lblBoxSaveStatus.Visible = false;
        this.lblMenuSaveSatus.Text = string.Empty;
        this.lblBoxSaveStatus.Text = string.Empty;
        switch (liIndex)
        {
            case 0:
                // new menu                
                this.lblMenuSaveSatus.Visible = true;
                this.setMenuDetail(null, "New");
                break;
            case 1:
                // edit menu                
                this.lblMenuSaveSatus.Visible = true;
                break;
            case 2:
                // new box                
                this.lblBoxSaveStatus.Visible = true;
                this.setBoxDetail(null, "New");
                break;
            case 3:
                // edit box                
                this.lblBoxSaveStatus.Visible = true;
                break;
            case 4:
                // configuration manager
                break;
            case 5:
                // site log
                setSiteLoggData();
                break;
        }
        multiViewModuleManager.ActiveViewIndex = liIndex;
    }

    // This handles the save button clicking event in viewEditPage
    protected void btnSave_Click(object sender, EventArgs e)
    {
        digioz.MenuItem loMenuItem = new digioz.MenuItem();
        if (!(lblMenuID.Text == null || lblMenuID.Text == string.Empty))
        {
            loMenuItem.ID = int.Parse(lblMenuID.Text);
        }
        loMenuItem.Name = tbMenuName.Text;
        loMenuItem.ActionData = tbMenuActionData.Text;
        loMenuItem.ActionType = tbMenuActionType.Text;
        int boxid = Convert.ToInt32(cbBoxlist.SelectedValue);
        loMenuItem.BoxID = boxid;
        if (digioz.MenuItemManagement.SaveMenuItem(loMenuItem, this.lblMode.Text))
        {
            lblMenuSaveSatus.ForeColor = System.Drawing.Color.Green;
            lblMenuSaveSatus.Font.Bold = true;
            lblMenuSaveSatus.Text = (this.lblMode.Text == "New") ? "New item has been saved." : "The item has been updated.";
        }
        else
        {
            lblMenuSaveSatus.ForeColor = System.Drawing.Color.Red;
            lblMenuSaveSatus.Font.Bold = true;
            lblMenuSaveSatus.Text = (this.lblMode.Text == "New") ? "New item could not be saved." : "The item could not be updated.";
        }
        this.updateMenuItemList();
    }

    // This handles the edit button clicking event in ViewListPage
    protected void btnEdit_Click(object sender, EventArgs e)
    {
        if (this.lMenuItems.SelectedItem != null)
        {
            digioz.MenuItem loMenuItem = digioz.MenuItemManagement.GetMenuItemFromMenuName(this.lMenuItems.SelectedItem.Text);
            this.setMenuDetail(loMenuItem, "Update");
            multiViewModuleManager.ActiveViewIndex = 0;
        }
    }

    // This handles the delete button clicking event in ViewListPage
    protected void btnDelete_Click(object sender, EventArgs e)
    {
        if (this.lMenuItems.SelectedItem == null) return;
        int id = Convert.ToInt32(this.lMenuItems.SelectedItem.Value);
        digioz.MenuItem loMenuItem = new digioz.MenuItem();
        loMenuItem.ID = id;
        digioz.MenuItemManagement.DeleteMenuItem(loMenuItem);
        this.updateMenuItemList();

    }

    protected void btnSaveBox_Click(object sender, EventArgs e)
    {
        digioz.BoxItem loBoxItem = new digioz.BoxItem();
        if (!(lblBoxID.Text == null || lblBoxID.Text == string.Empty))
        {
            loBoxItem.ID = int.Parse(lblBoxID.Text);
        }
        loBoxItem.Name = tbBoxName.Text;
        loBoxItem.Permission = int.Parse(ddlPermission.SelectedValue);
        loBoxItem.ActionData = tbBoxActionData.Text;
        loBoxItem.ActionType = cbBoxActionTypes.Text;
        if (rbBoxLocationLeft.Checked)
        {
            loBoxItem.Location = "L";
        }
        else if (rbBoxLocationRight.Checked)
        {
            loBoxItem.Location = "R";
        }

        if (digioz.BoxItemManagement.SaveBoxItem(loBoxItem, this.lblMode.Text))
        {
            lblBoxSaveStatus.ForeColor = System.Drawing.Color.Green;
            lblBoxSaveStatus.Font.Bold = true;
            this.lblBoxSaveStatus.Text = (this.lblMode.Text == "New") ? "New item has been saved." : "The item has been updated.";
        }
        else
        {
            lblBoxSaveStatus.ForeColor = System.Drawing.Color.Red;
            lblBoxSaveStatus.Font.Bold = true;
            lblBoxSaveStatus.Text = (this.lblMode.Text == "New") ? "New item could not be saved" : "The item could not be updated.";

        }

        this.updateBoxItemList();
    }

    private void editBox(int piId)
    {
        digioz.BoxItemList loBoxItemList = digioz.BoxItemManagement.GetBoxItemList();
        foreach (digioz.BoxItem loBoxItem in loBoxItemList)
        {
            if (loBoxItem.ID == piId)
            {
                this.setBoxDetail(loBoxItem, "Update");
                break;
            }
        }
        multiViewModuleManager.ActiveViewIndex = 2;
    }

    private void deleteBox(int piId)
    {
        digioz.BoxItem loBoxItem = new digioz.BoxItem();
        loBoxItem.ID = piId;
        digioz.BoxItemManagement.DeleteBoxItem(loBoxItem);
        this.updateBoxItemList();
    }

    // This will move a box order up if piDirection < 0; or down if piDirection > 0. 
    private void moveBoxOrder(string psLocation, int piItemIndex, int piDirection)
    {
        int liIndexSwap;
        digioz.BoxItemList loBoxItemList;
        // loBoxItemMoving is clicked, loBoxItemReplacing will switch position with loBoxItemMoving
        digioz.BoxItem loBoxItemMoving, loBoxItemReplacing = new digioz.BoxItem();

        if (psLocation == "L")
        {
            loBoxItemList = digioz.BoxItemManagement.GetBoxItemListByLocation("L");
        }
        else
        {
            loBoxItemList = digioz.BoxItemManagement.GetBoxItemListByLocation("R");
        }
        if ((piDirection > 0 && piItemIndex == loBoxItemList.Count - 1) || (piDirection < 0 && piItemIndex == 0))
        {
            // Do nothing: trying to down the last one or up the first one
        }
        else
        {
            loBoxItemMoving = loBoxItemList[piItemIndex];
            if (piDirection < 0 && piItemIndex > 0)
            {
                loBoxItemReplacing = loBoxItemList[piItemIndex - 1];
            }
            else if (piDirection > 0 && piItemIndex < loBoxItemList.Count - 1)
            {
                loBoxItemReplacing = loBoxItemList[piItemIndex + 1];
            }
            liIndexSwap = loBoxItemMoving.Order;
            loBoxItemMoving.Order = loBoxItemReplacing.Order;
            loBoxItemReplacing.Order = liIndexSwap;
            digioz.BoxItemManagement.SaveBoxItem(loBoxItemMoving, "Update");
            digioz.BoxItemManagement.SaveBoxItem(loBoxItemReplacing, "Update");
            this.updateBoxItemList();
        }
    }

    protected void gridLeftBox_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int liIndex = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName.Equals("Edit"))
        {
            editBox(int.Parse(gridLeftBox.DataKeys[liIndex].Values["ID"].ToString()));
        }
        else if (e.CommandName.Equals("Delete"))
        {
            deleteBox(int.Parse(gridLeftBox.DataKeys[liIndex].Values["ID"].ToString()));
        }
        else if (e.CommandName.Equals("moveUp"))
        {
            this.moveBoxOrder("L", liIndex, -1);
        }
        else if (e.CommandName.Equals("moveDown"))
        {
            this.moveBoxOrder("L", liIndex, +1);
        }
    }

    protected void gridLeftBox_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridLeftBox.PageIndex = e.NewPageIndex;
        this.updateBoxItemList();

    }
    protected void gridRightBox_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridRightBox.PageIndex = e.NewPageIndex;
        this.updateBoxItemList();
    }

    protected void gridRightBox_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int liIndex = Convert.ToInt32(e.CommandArgument);
        if (e.CommandName.Equals("Edit"))
        {
            editBox(int.Parse(gridRightBox.DataKeys[liIndex].Values["ID"].ToString()));
        }
        else if (e.CommandName.Equals("Delete"))
        {
            deleteBox(int.Parse(gridRightBox.DataKeys[liIndex].Values["ID"].ToString()));
        }
        else if (e.CommandName.Equals("moveUp"))
        {
            this.moveBoxOrder("R", liIndex, -1);
        }
        else if (e.CommandName.Equals("moveDown"))
        {
            this.moveBoxOrder("R", liIndex, +1);
        }
    }

    private void setSiteLoggData()
    {
        this.gridSiteLog.DataSource = digioz.SiteLogManagement.GetSiteLogList();
        this.gridSiteLog.DataBind();
    }
    protected void btnRefresh_Click(object sender, EventArgs e)
    {
        setSiteLoggData();
    }
    protected void btnClearLog_Click(object sender, EventArgs e)
    {
        digioz.SiteLogManagement.DeleteSiteLog(DateTime.Now);
        setSiteLoggData();
    }
    protected void gridSiteLog_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridSiteLog.PageIndex = e.NewPageIndex;
        this.setSiteLoggData();
    }

    protected void gridConfigItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridConfigItems.PageIndex = e.NewPageIndex;
        setConfigData();
    }

    protected void gridConfigItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        int liIndex = e.RowIndex;
        int liID = int.Parse(gridConfigItems.DataKeys[liIndex].Values["ID"].ToString());
        digioz.Configuration loConfiguration = new digioz.Configuration();

        digioz.ConfigurationList loConfigurationList = digioz.ConfigurationManagement.GetConfigurationList();
        foreach (digioz.Configuration loConfigurationTemp in loConfigurationList)
        {
            if (loConfigurationTemp.ID == liID)
            {
                loConfiguration = loConfigurationTemp;
                break;
            }
        }
        if (loConfiguration.Removable != "Y")
        {
            lblConfigMessage.ForeColor = System.Drawing.Color.Red;
            lblConfigMessage.Font.Bold = true;
            lblConfigMessage.Text = "This item can't be deleted.";
        }
        else
        {
            lblConfigMessage.Text = "";
            digioz.ConfigurationManagement.DeleteConfiguration(loConfiguration);
        }
        this.setConfigData();
    }

    protected void gridConfigItems_RowEditing(object sender, GridViewEditEventArgs e)
    {
        this.lblMode.Text = "Update";
        ((BoundField)gridConfigItems.Columns[0]).ReadOnly = false;
        gridConfigItems.EditIndex = e.NewEditIndex;
        setConfigData();
    }

    protected void gridConfigItems_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        GridViewRow row = gridConfigItems.Rows[e.RowIndex];
        digioz.ConfigurationList loConfigurationList = digioz.ConfigurationManagement.GetConfigurationList();
        int trueRowIndex = (gridConfigItems.PageIndex * gridConfigItems.PageSize) + e.RowIndex;
        if (trueRowIndex < 0 || trueRowIndex >= loConfigurationList.Count) return;

        digioz.Configuration loConfiguration = loConfigurationList[trueRowIndex];

        loConfiguration.KeyName = ((TextBox)(row.Cells[0].Controls[0])).Text;
        loConfiguration.KeyValue = ((TextBox)(row.Cells[1].Controls[0])).Text;
        loConfiguration.Removable = "Y";

        gridConfigItems.EditIndex = -1;
        digioz.ConfigurationManagement.SaveConfiguration(loConfiguration, "Update");
        this.setConfigData();
    }

    protected void btnAddConfigItem_Click(object sender, EventArgs e)
    {
        this.lblMode.Text = "New";
        digioz.Configuration loConfiguration = new digioz.Configuration();
        loConfiguration.KeyName = "[Key Name]";
        loConfiguration.KeyValue = "[Key Value]";
        digioz.ConfigurationManagement.SaveConfiguration(loConfiguration, this.lblMode.Text);
        digioz.ConfigurationList loConfigurationList = digioz.ConfigurationManagement.GetConfigurationList();
        this.gridConfigItems.DataSource = loConfigurationList;

        int liCount = loConfigurationList.Count;
        int editIndex = (liCount - 1) % gridConfigItems.PageSize;
        int pageIndex = (liCount - 1) / gridConfigItems.PageSize;
        this.gridConfigItems.PageIndex = pageIndex;

        ((BoundField)gridConfigItems.Columns[0]).ReadOnly = false;
        gridConfigItems.EditIndex = editIndex;
        this.gridConfigItems.DataBind();
        lblConfigMessage.ForeColor = System.Drawing.Color.Green;
        lblConfigMessage.Font.Bold = true;
        lblConfigMessage.Text = "Item has been added.";
    }

    protected void gridConfigItems_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        if (lblMode.Text == "New")
        {
            int liID = int.Parse(gridConfigItems.DataKeys[e.RowIndex].Values["ID"].ToString());
            digioz.Configuration loConfiguration = new digioz.Configuration();

            digioz.ConfigurationList loConfigurationList = digioz.ConfigurationManagement.GetConfigurationList();
            foreach (digioz.Configuration loConfigurationTemp in loConfigurationList)
            {
                if (loConfigurationTemp.ID == liID)
                {
                    loConfiguration = loConfigurationTemp;
                    break;
                }
            }
            digioz.ConfigurationManagement.DeleteConfiguration(loConfiguration);
        }
        gridConfigItems.EditIndex = -1;
        this.setConfigData();
    }

    protected void gridLeftBox_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void gridLeftBox_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void gridRightBox_RowEditing(object sender, GridViewEditEventArgs e)
    {

    }
    protected void gridRightBox_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {

    }
    protected void gridLeftBox_RowCreated(object sender, GridViewRowEventArgs e)
    {

    }
}
