using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.IO;
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 System.Data.SqlClient;
using System.Collections.Generic;
using digioz.PictureModule;
using digioz;
using digioz.admin;
using System.Drawing.Imaging;

public partial class controls_admin_PictureManager : System.Web.UI.UserControl
{
    private string lsError;
    private const string csDefaultCategory = "Default Category";

    protected void Page_Load(object sender, EventArgs e)
    {
        lblMessage.Visible = false;
        lblMessage.Text = "";
        if (!IsPostBack)
        {
            BindData();
        }
    }

    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        txtPictureId.Value = "";
        switch (e.Item.Value)
        {
            case "Photos":
                BindData();
                MultiView1.SetActiveView(Tab1);
                break;
            case "Add":
                SetEditDetails();
                MultiView1.SetActiveView(Tab2);
                break;
        }
    }

    public void page(object sender, DataGridPageChangedEventArgs e)
    {
        pictureGrid.CurrentPageIndex = e.NewPageIndex;
        BindData();
    }

    public void Edit(object s, DataGridCommandEventArgs e)
    {
        txtPictureId.Value = pictureGrid.DataKeys[e.Item.ItemIndex].ToString();
        SetEditDetails();
        MultiView1.ActiveViewIndex = 1;
    }

    public void Delete(object s, DataGridCommandEventArgs e)
    {
        txtPictureId.Value = pictureGrid.DataKeys[e.Item.ItemIndex].ToString();
        DeletePictureFiles(e.Item.Cells[1].Text);
        PictureInfoManagement.DeletePictureInfo(Convert.ToInt16(txtPictureId.Value));
        BindData();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SavePictureData();
        SetEditDetails();
    }

    protected void btnNext_Click(object sender, EventArgs e)
    {
        FlipPicture("F");
    }

    protected void btnPrev_Click(object sender, EventArgs e)
    {
        FlipPicture("B");
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    /// Note: Using the PostBackUrl property prevents Click from firing.
    /// (Probably tries to fire event on destination page and fails)
    /// So has to use CommandArgument instead
    protected void btnAddCategory_Command(object sender, CommandEventArgs e)
    {
        // Navigate to Category Manager
        if (e.CommandName == "Add")
        {
            Response.Redirect(btnAddCategory.CommandArgument);
        }
    }

    protected void pictureGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {
        /* It seems that is the Eval "function" that is trimming the new line 
        sequence.Encode it. */

        if ((e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            ((Image)e.Item.FindControl("Image1")).ImageUrl = GetPicture(((PictureInfo)e.Item.DataItem).Serverfilename);
            Label description = (Label)e.Item.FindControl("Description");

            if (description != null)
            {
                /* From MSDN : Text is not HTML encoded before it is displayed
                in the BoundColumn. */
                description.Text = Server.HtmlEncode(description.Text);

                // Convert New line sequences
                description.Text = Utility.EncodeNewLine(description.Text);
            }
        }
    }

    #region Functions

    public void BindData()
    {
        int liPictureId;
        pictureGrid.DataSource = PictureInfoManagement.GetPictureInfoList("");
        pictureGrid.DataBind();

        if (!IsPostBack)
        {
            BindLists();
            int.TryParse(Request["PictureId"], out liPictureId);
            txtPictureId.Value = liPictureId.ToString();
            SetEditDetails();
        }
    }

    private void BindLists()
    {
        // Fill the category dropdown list
        ddlCategory.DataSource = CategoryInfoManagement.GetCategoriesList("Picture");
        ddlCategory.DataBind();

        // Fill the Uploader dropdoen list
        ddlUploader.DataSource = UserManagement.GetUserList();
        ddlUploader.DataBind();
    }

    public string GetPicture(string psFileName)
    {
        string lsFullPath = "~/pictures/" + "tn_" + psFileName + "?n=" + Guid.NewGuid().ToString();
        return lsFullPath;
    }

    public void SavePictureData()
    {
        int liPictureId;
        string lsSaveMode;
        PictureInfo loRecord;
        bool lbRetValue = false;
        string lsMessage;

        if (Page.IsValid)
        {
            int.TryParse(txtPictureId.Value, out liPictureId);
            if (liPictureId > 0)
            {
                loRecord = PictureInfoManagement.GetPictureInfo(liPictureId);
                lsSaveMode = "Update";
            }
            else
            {
                if (!fudPictureFile.HasFile)
                {
                    DisplayMessage("Please select a file to upload", true);
                    return;
                }
                lsSaveMode = "New";
                loRecord = new PictureInfo();
            }
            if (fudPictureFile.HasFile)
            {
                if (!SavePicture())
                {
                    return;
                }
                loRecord.Serverfilename = txtServerFileName.Value;
                loRecord.Mimetype = fudPictureFile.PostedFile.ContentType;
            }
            loRecord.FileName = Utility.ConvertHtmlFilterInput(txtPictureName.Text);
            loRecord.Description = Utility.ConvertHtmlFilterInput(txtPicDesc.Text);
            loRecord.Category = Utility.ConvertHtmlFilterInput(ddlCategory.SelectedValue);
            loRecord.Uploadtime = Convert.ToDateTime(txtDateTime.Text);
            loRecord.Uploader = Utility.ConvertHtmlFilterInput(ddlUploader.SelectedValue);

            lbRetValue = PictureInfoManagement.SavePictureInfo(loRecord, lsSaveMode);
            txtPictureId.Value = loRecord.ID.ToString();
            lsMessage = (lbRetValue
                ? string.Format("Photo '{0}' has been sucessfully updated...<br/>",
                                                Server.HtmlEncode(txtPictureName.Text))
                : string.Format("Failed to update Photo '{0}'...<br/>",
                                                Server.HtmlEncode(txtPictureName.Text)));
            DisplayMessage(lsMessage, lbRetValue);
        }
        BindData();
    }

    public void DeletePictureFiles(string psServerFileName)
    {
        string lsServerPath = Server.MapPath("~") + "\\pictures\\";
        DirectoryInfo loDir = new DirectoryInfo(lsServerPath);
        foreach (FileInfo loFileInfo in loDir.GetFiles())
        {
            if (loFileInfo.FullName == lsServerPath + psServerFileName ||
                loFileInfo.FullName == lsServerPath + "tn_" + psServerFileName)
            {
                loFileInfo.Delete();
            }
        }
    }

    /// <summary>
    /// Next and Previous function
    /// </summary>
    /// <param name="loPictureDirection"></param>
    public void FlipPicture(string psDirection)
    {
        int liOldPictureId, liNewPictureId;
        psDirection = (psDirection == "B" ? "B" : "F");
        if (int.TryParse(txtPictureId.Value, out liOldPictureId))
        {
            liNewPictureId = PictureInfoManagement.FlipPicture(liOldPictureId, psDirection, "ALL");
            txtPictureId.Value = liNewPictureId.ToString();
            SetEditDetails();
        }
    }

    private void ClearControls()
    {
        txtPictureName.Text = "";
        txtPicDesc.Text = "";
        txtDateTime.Text = "";
        ddlUploader.SelectedValue = "";
        txtServerFileName.Value = "";
        imgCurrentImage.Visible = false;
        ddlCategory.SelectedItem.Selected = false;
        ddlCategory.Items.FindByText(csDefaultCategory).Selected = true;
        btnPrev.Visible = false;
        btnNext.Visible = false;
    }

    /// <summary>
    /// Set the input fields for the picture that we are editing
    /// </summary>
    /// <param name="poVideo"></param>
    private void SetEditDetails()
    {
        ListItem loListItem;
        int liPageId = -1;
        string lsPageName = "";
        AdminMenuItem loAdminMenuItem;
        int liPictureId;
        PictureInfo loPictureInfo;

        ClearControls();

        int.TryParse(txtPictureId.Value, out liPictureId);
        if (liPictureId > 0)
        {
            loPictureInfo = PictureInfoManagement.GetPictureInfo(liPictureId);
            txtPictureName.Text = loPictureInfo.FileName;
            txtPicDesc.Text = loPictureInfo.Description;

            ddlCategory.SelectedItem.Selected = false;
            loListItem = ddlCategory.Items.FindByText(loPictureInfo.Category);
            if (loListItem != null)
            {
                loListItem.Selected = true;
            }
            txtDateTime.Text = loPictureInfo.Uploadtime.ToShortDateString() + " " + loPictureInfo.Uploadtime.ToShortTimeString();

            ddlUploader.SelectedItem.Selected = false;
            loListItem = ddlUploader.Items.FindByValue(loPictureInfo.Uploader);
            if (loListItem != null)
            {
                loListItem.Selected = true;
            }
            else
            {
                loListItem = ddlUploader.Items.FindByValue("");
                loListItem.Enabled = true;
                loListItem.Selected = true;
            }

            txtServerFileName.Value = loPictureInfo.Serverfilename;

            imgCurrentImage.Visible = true;
            imgCurrentImage.ImageUrl = GetPicture(loPictureInfo.Serverfilename);

            btnPrev.Visible = true;
            btnNext.Visible = true;
        }

        // Navigation path for adding a new category
        if (int.TryParse(Request["id"], out liPageId))
        {
            loAdminMenuItem = AdminMenuItemManagement.GetAdminMenuItemFromPageID(liPageId);
            lsPageName = loAdminMenuItem.Name;
        }

        loAdminMenuItem = AdminMenuItemManagement.GetAdminMenuItemFromMenuName("Category Manager");

        btnAddCategory.CommandArgument =
            string.Format("~/Admin.aspx?id={0}&PreviousPage={1}&PreviousTitle={2}&PictureId={3}",
            Server.UrlEncode(loAdminMenuItem.ID.ToString()), // id of the target page
            Server.UrlEncode(Request.Url.ToString()),   // Url of the current page (to navigate back to)
            Server.UrlEncode(lsPageName),                    // Name of the current page
            Server.UrlEncode(txtPictureId.Value));
    }

    private bool SavePicture()
    {
        string lsExt, lsFilename, lsPath;
        Extensions loExtension = null;

        lsPath = Server.MapPath("~") + "\\pictures\\";

        if (txtServerFileName.Value == "")
        {
            lsFilename = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
        }
        else
        {
            lsFilename = Path.GetFileNameWithoutExtension(txtServerFileName.Value);
        }

        lsExt = Path.GetExtension(fudPictureFile.PostedFile.FileName.ToLower());
        
        if (!ExtensionsManagement.IsFileValid(lsExt, "IMAGE", out loExtension))
        {
            //TODO: Build list from database
            DisplayMessage("Only accept .jpg, .gif, .bmp, format", true);
            return false;
        }

        if (txtServerFileName.Value != lsFilename + lsExt)
        {
            DeletePictureFiles(txtServerFileName.Value);
        }

        lsPath += lsFilename + lsExt;

        fudPictureFile.PostedFile.SaveAs(lsPath);

        System.Drawing.Image mymap = System.Drawing.Image.FromFile(lsPath);
        int width = 0, height = 0;
        if (mymap.Width > mymap.Height)
        {
            width = 150;
            height = Convert.ToInt32(((float)mymap.Height / (float)mymap.Width) * 150);
        }
        else
        {
            height = 150;
            width = Convert.ToInt32(((float)mymap.Width / (float)mymap.Height) * 150);
        }
        System.Drawing.Image thumbnail = mymap.GetThumbnailImage(width, height, null, IntPtr.Zero);
        ImageFormat extFormat = ImageFormat.Jpeg;
        switch (lsExt)
        {
            case ".jpg":
                extFormat = ImageFormat.Jpeg;
                break;
            case ".gif":
                extFormat = ImageFormat.Gif;
                break;
            case ".png":
                extFormat = ImageFormat.Png;
                break;
            case ".bmp":
                extFormat = ImageFormat.Bmp;
                break;
        }
        thumbnail.Save(Server.MapPath("~") + "/pictures/tn_" + lsFilename + lsExt, extFormat);
        thumbnail.Dispose();
        mymap.Dispose();

        txtServerFileName.Value = lsFilename + lsExt;

        return true;
    }

    private void DisplayMessage(string psMessage, bool pbIsError)
    {
        lblMessage.Visible = true;
        lblMessage.CssClass = pbIsError ? "messageOk" : "messageError";
        lblMessage.Text = psMessage;
    }

    #endregion


}