using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using digioz;
using digioz.PictureModule;


public partial class controls_PictureUpload : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        // Check for Login ----------------------------------------------------------

        if (Session["userid"] == null || Convert.ToString(Session["userid"]) == String.Empty)
        {
            Response.Redirect("Login.aspx");
        }

        if (!IsPostBack)
        {
            // Get all picture categories
            ddlCategory.DataSource = CategoryInfoManagement.GetCategoriesList("Picture");
            ddlCategory.DataTextField = "CategoryName";
            ddlCategory.DataBind();
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        bool lbRetVal = false;
        string lsExt;
        Extensions loExtension = null;

        if (!FileUpload1.HasFile)
        {
            DisplayResult(Label1,
                          true, // error message
                          "Please select a file to upload");
            return;
        }

        if (string.IsNullOrEmpty(TextBoxTitle.Text))
        {
            DisplayResult(Label1,
                          true, // error message
                          "Please complete Title");
            return;
        }

        lsExt = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName.ToLower());
        if (!ExtensionsManagement.IsFileValid(lsExt, "IMAGE", out loExtension ))                    
        {
            //TODO: Build list from database
            DisplayResult(Label1,
                          true, // error message
                          "Only accept .jpg, .gif, .bmp, format");
            return;
        }

        string filename = 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();
        string serverPath = Server.MapPath("~") + "\\pictures\\" + filename + lsExt;
        FileUpload1.PostedFile.SaveAs(serverPath);

        System.Drawing.Image mymap = System.Drawing.Image.FromFile(serverPath);
        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_" + filename + lsExt, extFormat);
        thumbnail.Dispose();
        mymap.Dispose();
        PictureInfo loRecord = new PictureInfo();
        loRecord.FileName = Utility.ConvertHtmlFilterInput(TextBoxTitle.Text);
        loRecord.Description = Utility.ConvertHtmlFilterInput(TextBoxDescription.Text);
        loRecord.Category = Utility.ConvertHtmlFilterInput(ddlCategory.SelectedValue);
        loRecord.Serverfilename = filename + lsExt;
        loRecord.Uploadtime = DateTime.Now;
        loRecord.Uploader = Convert.ToString(Session["userid"]);
        
        //If seems that the MIME type returned by IE is not always what we expect
        // Example "image/pjpeg" for ".jpg"
        // So look it up in the tblExtensions table instead.
        if (null != loExtension)
        {
            loRecord.Mimetype = loExtension.MimeType;
        }
        else
        {
            loRecord.Mimetype = FileUpload1.PostedFile.ContentType;
        }
        
        lbRetVal = PictureInfoManagement.SavePictureInfo(loRecord, "New");

        if (lbRetVal)
        {
            Label1.CssClass = "messageOk";
            Label1.Text = string.Format("File {0} was uploaded.",
                                        Server.HtmlEncode(loRecord.FileName));
        }
        else
        {
            Label1.CssClass = "messageError";
            Label1.Text = string.Format("Failed to upload file {0}.", 
                                        Server.HtmlEncode(loRecord.FileName));
        }
    }


    /// <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";
        }
    }


}
