using System;
using System.Data;
using System.Configuration;
using System.Collections;
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;
using digioz;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;

public partial class controls_admin_ForumManagement : System.Web.UI.UserControl
{
    public Forum coCurrentForum;
    public int ciForumID;

    protected void Page_Load(object sender, EventArgs e)
    {
        setDataOnLoad();
        if (!Page.IsPostBack)
        {
            MultiView1.ActiveViewIndex = 1;
        }
    }

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
    }

    private void setDataOnLoad()
    {

        if (MultiView1.ActiveViewIndex == 0)
        {
            lblAddForumMsg.Text = "";
        }
        if (MultiView1.ActiveViewIndex == 1)
        {
            this.lblForumListMsg.Text = "";
            setForumData();
        }
        if (MultiView1.ActiveViewIndex == 2)
        {
            lblUpdateForumMsg.Text = "";
        }
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        int index = Int32.Parse(e.Item.Value);
        if (index == 0)
        {
            coCurrentForum = new Forum();
            coCurrentForum.ID = -1;
        }
        MultiView1.ActiveViewIndex = index;
    }

    protected void MultiView1_ActiveViewChanged(object sender, EventArgs e)
    {
        if (MultiView1.ActiveViewIndex > 1)
        {
            Menu2.Items[MultiView1.ActiveViewIndex - 2].Selected = true;
        }
        else
        {
            Menu2.Visible = false;
            Menu1.Items[MultiView1.ActiveViewIndex].Selected = true;
        }

        if (MultiView1.ActiveViewIndex == 0)
        {

        }
        if (MultiView1.ActiveViewIndex == 1)
        {
            setForumData();
        }

        if (MultiView1.ActiveViewIndex == 2)
        {

        }
    }

    internal void setForumData()
    {
        gridForums.DataSource = digioz.ForumManagement.GetForumList();
        gridForums.DataBind();
    }

    protected void gridForums_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gridForums.PageIndex = e.NewPageIndex;
        setForumData();
    }

    private void addRowSpecifics(GridView gv, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            Forum forum = e.Row.DataItem as Forum;
            foreach (DataControlField dcf in gv.Columns)
            {

                if (dcf.GetType().Equals(typeof(CommandField)))
                {
                    CommandField cmf = dcf as CommandField;
                    if (cmf != null && (cmf.ShowDeleteButton))
                    {
                        e.Row.Cells[gv.Columns.IndexOf(dcf)].Attributes
                              .Add("onclick", "return confirm(\"Are you sure you want to delete this forum?\")");
                    }
                }
                else if (dcf.GetType().Equals(typeof(ButtonField)))
                {
                    if (e.Row.RowIndex == 0 && ((ButtonField)dcf).CommandName.Equals("moveUp"))
                    {
                        e.Row.Cells[gv.Columns.IndexOf(dcf)].Controls.Clear();
                    }
                    else if (e.Row.RowIndex == (((ICollection)gv.DataSource).Count - 1) && ((ButtonField)dcf).CommandName.Equals("moveDown"))
                    {
                        e.Row.Cells[gv.Columns.IndexOf(dcf)].Controls.Clear();
                    }
                }
            }
        }
    }

    protected void gridForums_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        // The index does not appear to account for paging.
        // If you select index 3 on page 2, the index is 3,
        // not 8 as expected for page size = 5
        int liIndex = (gridForums.PageIndex * gridForums.PageSize) + e.RowIndex;
        ForumList loForumList = ForumManagement.GetForumList();
        //coCurrentForum = loForumList[e.RowIndex];
        coCurrentForum = loForumList[liIndex];

        if (!digioz.ForumManagement.DeleteForum(coCurrentForum))
        {
            setMessage(lblForumListMsg, "Delete failed!", true);
        }
        else
        {
            setMessage(lblForumListMsg, "Delete succesful!", false);
            setForumData();
        }
    }

    private void setMessage(Label pLabel, string pMessage, bool pError)
    {
        pLabel.Text = pMessage;
        pLabel.CssClass = pError ? "messageError" : "messageOk";
    }

    protected void gridForums_RowEditing(object sender, GridViewEditEventArgs e)
    {
        ForumList loForumList = ForumManagement.GetForumList();

        // The index does not appear to account for paging.
        // If you select index 3 on page 2, the index is 3,
        // not 8 as expected for page size = 5
        int liIndex = (gridForums.PageIndex * gridForums.PageSize) + e.NewEditIndex;
        //coCurrentForum = loForumList[e.NewEditIndex];
        coCurrentForum = loForumList[liIndex];
        Session["ForumEditIndex"] = coCurrentForum.ID;
        txtEditForumName.Text = coCurrentForum.ForumName;
        txtEditForumDesc.Text = coCurrentForum.ForumDesc;
        txtEditForumLink.Text = coCurrentForum.ForumLink;
        // Invisible text box. Used to hold Image file name.
        // Otherwise, it could be overwritten by the update
        txtEditForumImage.Text = coCurrentForum.ForumImage;
        cboEditForumType.SelectedValue = coCurrentForum.ForumType.ToString();
        cboEditForumStatus.SelectedValue = coCurrentForum.ForumStatus.ToString();
        MultiView1.ActiveViewIndex = 2;
        Menu2.Visible = true;
    }

    protected void gridForums_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
    }

    protected void gridForums_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
    }
    protected void gridForums_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        addRowSpecifics((GridView)sender, e);
    }

    //public int GetTotalIndexFromGrid(GridView poView, int piIndex)
    //{
    //    return (poView.PageSize * poView.PageIndex) + piIndex;
    //}

    protected void gridForums_RowCommand(object sender, GridViewCommandEventArgs e)
    {

        if (e.CommandName.Equals("moveUp") || e.CommandName.Equals("moveDown"))
        {
            int index = Convert.ToInt32(e.CommandArgument);
            //if (!this.AdminPage.OkToRowCommand(gridForums, index)) return;
            int step = e.CommandName.Equals("moveUp") ? -1 : 1;
            //BindingList<Forum> data = gridForums.DataSource as BindingList<Forum>;
            //Forum forum = data[AdminPage.getTotalIndexFromGrid(gridForums, index)];
            //digioz.ForumManagement.MoveForum(forum, step);
            ForumList loForumList = ForumManagement.GetForumList();
            Forum loSwapForum;

            if (index == loForumList.Count && step == 1 || index == 0 && step == -1)
            {
                return;
            }

            loSwapForum = loForumList[index + step];

            coCurrentForum = loForumList[index];
            digioz.ForumManagement.MoveForum(coCurrentForum, loSwapForum, step);
        }
    }

    protected void btnSaveForum_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Forum loForum = new Forum();
            loForum.ID = -1;
            loForum.ForumName = txtForumName.Text;
            loForum.ForumDesc = txtForumDesc.Text;
            loForum.ForumLink = txtForumLink.Text;
            loForum.ForumType = Convert.ToInt16(cboForumType.SelectedValue);
            loForum.ForumStatus = Convert.ToInt16(cboForumStatus.SelectedValue);
            loForum.ForumImage = string.Empty;
            bool lbValidFile = true;

            // if there is an image file, then validate it, resize it and save it
            if (uploadForumImage.HasFile)
            {
                lbValidFile = HandleForumImage(uploadForumImage, loForum);
            }

            if (lbValidFile)
            {
                if (ForumManagement.Save(loForum))
                {
                    lblAddForumMsg.CssClass = "messageOk";
                    lblAddForumMsg.Text = "Forum saved.";
                }
                else
                {
                    lblAddForumMsg.CssClass = "messageError";
                    lblAddForumMsg.Text = "Failed to save forum.";
                }

                //clear controls
                txtForumName.Text = "";
                txtForumDesc.Text = "";
                //txtForumImage.Text = "";
                txtForumLink.Text = "";
                cboForumType.SelectedIndex = 0;
                cboForumStatus.SelectedIndex = 0;
                txtForumName.Focus();
            }
            else
            {
                lblAddForumMsg.CssClass = "messageError";
                lblAddForumMsg.Text =
                    string.Format("This image file format is not valid!");
                uploadForumImage.Focus();
            }
        }
        
    }
    protected void btnEditSaveForum_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            Forum loForum = new Forum();
            loForum.ID = Convert.ToInt16(Session["ForumEditIndex"]);
            loForum.ForumName = txtEditForumName.Text;
            loForum.ForumDesc = txtEditForumDesc.Text;
            loForum.ForumLink = txtEditForumLink.Text;
            loForum.ForumImage = txtEditForumImage.Text;
            loForum.ForumType = Convert.ToInt16(cboEditForumType.SelectedValue);
            loForum.ForumStatus = Convert.ToInt16(cboEditForumStatus.SelectedValue);
            bool lbValidFile = true;

            // if there is an image file, then validate it, resize it and save it
            // This will replace any existing file.
            if (EditForumImageUpload.HasFile)
            {
                lbValidFile = HandleForumImage(EditForumImageUpload, loForum);
            }

            if (lbValidFile)
            {
                if (ForumManagement.Update(loForum))
                {
                    lblUpdateForumMsg.CssClass = "messageOk";
                    lblUpdateForumMsg.Text = "Forum updated.";

                    //clear controls
                    txtEditForumDesc.Text = "";
                    txtEditForumLink.Text = "";
                    cboEditForumType.SelectedIndex = 0;
                    cboEditForumStatus.SelectedIndex = 0;
                }
                else
                {
                    lblUpdateForumMsg.CssClass = "messageError";
                    lblUpdateForumMsg.Text = "Forum update failed.";
                }
                
                txtEditForumName.Focus();
            }
            else
            {
                lblUpdateForumMsg.CssClass = "messageError";
                lblUpdateForumMsg.Text =
                    string.Format("This image file format is not valid!");
                EditForumImageUpload.Focus();
            }
        }
    }

    /// <summary>
    ///  Resize uploaded image and save to picture directory 
    /// </summary>
    /// <param name="psFileName"></param>
    private void FormatAndSaveImage(string psFileName,
                                    FileUpload poImageSource)
    {
        System.Drawing.Image forumImage = 
                System.Drawing.Image.FromStream(poImageSource.FileContent);
        int liWidth = 0;
        int liHeight = 0;

        // If either side is over 100, then resize
        if ( (forumImage.Width > 100 ) || (forumImage.Height > 100))
        {
            if (forumImage.Width > forumImage.Height)
            {
                liWidth = 100;
                liHeight = Convert.ToInt32(((float)forumImage.Height / (float)forumImage.Width) * 100);
            }
            else
            {
                liHeight = 100;
                liWidth = Convert.ToInt32(((float)forumImage.Width / (float)forumImage.Height) * 100);
            }

        }

        string lsFileExt = System.IO.Path.GetExtension(psFileName.ToLower());
        System.Drawing.Image resizedImage = forumImage.GetThumbnailImage(
                                                    liWidth,
                                                    liHeight,
                                                    null,
                                                    IntPtr.Zero);
        ImageFormat extFormat = ImageFormat.Jpeg;
        switch (lsFileExt)
        {
            case ".jpg":
                extFormat = ImageFormat.Jpeg;
                break;
            case ".gif":
                extFormat = ImageFormat.Gif;
                break;
            case ".png":
                extFormat = ImageFormat.Png;
                break;
            case ".bmp":
                extFormat = ImageFormat.Bmp;
                break;
        }

        psFileName = string.Format("~/pictures/{0}", psFileName);
        resizedImage.Save(Server.MapPath(psFileName), extFormat);
        resizedImage.Dispose();
        forumImage.Dispose();
    }


    /// <summary>
    /// Validate file and save to disk
    /// </summary>
    /// <param name="poImageSource"></param>
    /// <param name="poForum"></param>
    /// <returns></returns>
    private bool HandleForumImage(FileUpload  poImageSource,
                                  Forum       poForum)
    {
        bool lbImageFileValid = false;

        string lsFileName = poImageSource.PostedFile.FileName.ToLower();
        string lsFileExt = System.IO.Path.GetExtension(lsFileName);
        string lsFormattedName = string.Format("{0}_icon{1}",
                                              poForum.ForumName,
                                              lsFileExt);
        Extensions loExtension = null;
        lbImageFileValid = ExtensionsManagement.IsFileValid(lsFileExt,
                                                  "IMAGE",
                                                  out loExtension);
        if (lbImageFileValid)
        {
            FormatAndSaveImage(lsFormattedName, poImageSource);
            poForum.ForumImage = lsFormattedName;
        }

        return lbImageFileValid;
    }
}

