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 System.Drawing;
using System.Drawing.Imaging;
using digioz.PictureModule;
using digioz.VideoModule;
using digioz;

public partial class controls_ForumPosting : System.Web.UI.UserControl
{
    PortalSettings coPortalSettings;
    public string csForumName, csTopicResponseSubject;
    public int ciForumID, ciTopicID;
    public string csPage, csMode;
    const long MAX_LENGTH = 4000000;
    bool lbFileIsOk = false;

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

        // Get Refering Page ---------------------------------------------------------

        if (Session["referringURL"] == null)
        {
            try
            {
                Session["referringURL"] = Request.UrlReferrer.ToString();
            }
            catch
            {
                Session["referringURL"] = String.Empty;
            }
        }
        
        // Load Settings -------------------------------------------------------------

        coPortalSettings = PortalSettingsManagement.GetPortalSettings();

        // Set some query string parameters ------------------------------------------
        try
        {
            ciForumID = Convert.ToInt16(Request.QueryString["forum"]);
        }
        catch
        {
            ciForumID = 1;
        }

        try
        {
            ciTopicID = Convert.ToInt16(Request.QueryString["topic"]);
        }
        catch
        {
            ciTopicID = 0;
        }

        try
        {
            csMode = Convert.ToString(Request.QueryString["mode"]);
        }
        catch
        {
            csMode = "post";
        }

        if (ciForumID == 0)
        {
            ciForumID = 1;
        }

        try
        {
            csPage = Server.UrlEncode(Convert.ToString(Request.QueryString["page"]));
        }
        catch
        {
            csPage = String.Empty;
        }

        // Get Forum Name ----------------------------------------------------------------

        csForumName = ForumManagement.GetForumName(ciForumID); 
        if (csMode == "reply")
        {
            csTopicResponseSubject = ForumTopicManagement.GetForumTopicTitle(ciTopicID); 
            txtSubject.Text = "RE: " + csTopicResponseSubject;
        }

        // Load Forum Navigation ---------------------------------------------------------

        lblNavigation.Text = LoadForumNavigation();

        if (!IsPostBack)
        {
            BindCategoryData();
        }

        lblPrompt.Text = string.Empty;
    }

    /// <summary>
    /// Number of attachments in this post
    /// </summary>
    private int Attachments
    {
        get
        {
            return (ViewState["Attachments"] == null)? 0 : (int)ViewState["Attachments"];
        }

        set
        {
            ViewState.Add("Attachments", value);
        }
    }

    private string LoadForumNavigation()
    {
        string lsNavigationString = String.Empty;

        lsNavigationString = "<a href=\"Default.aspx?page=" + Server.UrlEncode(digioz.Encryption64.Encrypt("Forum", coPortalSettings.URLEncryptionKey)) + "\"> Index </a>";
        lsNavigationString += " &gt; ";
        lsNavigationString += "<a href=\"Default.aspx?page=" + Server.UrlEncode(digioz.Encryption64.Encrypt("Forum View", coPortalSettings.URLEncryptionKey)) + "&forum=" + ciForumID + "\">" + csForumName + "</a>";

        return lsNavigationString;
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        string lsSubject = Utility.ConvertHtmlFilterInput(txtSubject.Text);
        string lsMessage = Utility.ConvertHtmlFilterInput(txtMessage.Text);
        DateTime ldCurrentDateTime = DateTime.Now;
        string lsDateTime = ldCurrentDateTime.ToString();
        string lsTmpRURL = Convert.ToString(Session["referringURL"]);
        int liAttachment = 0;

        if (lsSubject == String.Empty || lsMessage == String.Empty)
        {
            lblPrompt.Text = "Please enter both Subject and Message.";
            return;
        }

        if (Attachments > 0)
        {
            liAttachment = 1;
        }

        ForumPost loForumPost = new ForumPost();

        if (csMode == "post")
        {
            loForumPost.ForumID = ciForumID;
            loForumPost.PostSubject = lsSubject;
            loForumPost.PostText = lsMessage;
            loForumPost.PostTime = Convert.ToDateTime(lsDateTime);
            loForumPost.PosterID = Convert.ToInt32(Session["userid"]);
            loForumPost.PosterName = Convert.ToString(Session["username"]);
            loForumPost.PosterIP = Convert.ToString(Session["visitorIP"]);
            loForumPost.PostAttachment = liAttachment;
            ForumPostManagement.SaveForumPost(loForumPost, "post");
        }
        else if (csMode == "reply")
        {
            loForumPost.TopicID = ciTopicID;
            loForumPost.ForumID = ciForumID;
            loForumPost.PosterID = Convert.ToInt32(Session["userid"]);
            loForumPost.PosterName = Convert.ToString(Session["username"]);
            loForumPost.PosterIP = Convert.ToString(Session["visitorIP"]);
            loForumPost.PostTime = Convert.ToDateTime(lsDateTime);
            loForumPost.PostSubject = lsSubject;
            loForumPost.PostText = lsMessage;
            loForumPost.PostAttachment = liAttachment;
            ForumPostManagement.SaveForumPost(loForumPost, "reply");
        }

        // Reset Attachments count
        Attachments = 0;
        Session["referringURL"] = null;
        Response.Redirect(lsTmpRURL);
    }

    /// <summary>
    ///  Handle files upload
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string lsFileExt = System.IO.Path.GetExtension(txtAttachment.PostedFile.FileName.ToLower());
        string lsFileType;
        Extensions loExtension = null;

        if (!txtAttachment.HasFile)
        {
            lblPrompt.Text = "Please select a file to upload";
            return;
        }

        HttpPostedFile loFile = (HttpPostedFile)(txtAttachment.PostedFile);
        if (loFile.ContentLength > MAX_LENGTH)
        {
            lblPrompt.Text = "The file size exceeded limit.";
            lblAttachments.Font.Bold = true;
            lblAttachments.ForeColor = System.Drawing.Color.Blue;
            return;
        }

        if (string.IsNullOrEmpty(TextBoxTitle.Text))
        {
            lblPrompt.Text = "Please complete Title";
            return;
        }

        if (ddlCategoryType.SelectedValue == "Picture")
        {
            lsFileType = "IMAGE";
        }
        else
        {
            lsFileType = "VIDEO";
        }

        lbFileIsOk = ExtensionsManagement.IsFileValid(lsFileExt, 
                                                      lsFileType,
                                                      out loExtension);
        if (!(lbFileIsOk))
        {
            lblPrompt.Text =
                string.Format("This file format is not accepted for {0} upload !",
                             lsFileType.ToLower());
            return;
        }

        int liFileContentLength = loFile.ContentLength;
        //string lsFileExt = txtAttachment.PostedFile.FileName.ToLower().Substring(txtAttachment.PostedFile.FileName.ToLower().LastIndexOf("."));
        string 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();
        
        //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.
        string lsMime;
        if (null != loExtension)
        {
            lsMime = loExtension.MimeType;
        }
        else
        {
            lsMime = txtAttachment.PostedFile.ContentType;
        }

        SaveAttachmentToDisk(lsFileExt, lsFilename);                                                          
        SaveAttachmentToDatabase(lsFilename+lsFileExt, 
                                 liFileContentLength,
                                 lsMime);
        TextBoxTitle.Text = String.Empty;
        TextBoxDescription.Text = String.Empty;

        // Keep track of attachments
        Attachments += 1;
        lblAttachments.Text += lsFilename + lsFileExt + "<br />";
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void ddlCategoryType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindCategoryData();
    }

    /// <summary>
    /// Populate category DropDownList
    /// </summary>
    private void BindCategoryData()
    {
        // Get all picture or video categories
        ddlCategory.DataSource = CategoryInfoManagement.GetCategoriesList(ddlCategoryType.SelectedValue);
        ddlCategory.DataTextField = "CategoryName";
        ddlCategory.DataBind();

        ddlCategory.Items.Insert(0, "Default Category");
    }

    /// <summary>
    /// Save attachment file to disk
    /// </summary>
    private void SaveAttachmentToDisk(string psFileExt,
                                   string psFilename)
    {
        if (txtAttachment.PostedFile.ContentType.Contains("image/"))
        {
            SavePictureToDisk(psFileExt, psFilename);
        }
        else if (txtAttachment.PostedFile.ContentType.Contains("video/"))
        {
            SaveVideoToDisk(psFileExt, psFilename);
        }
    }

    /// <summary>
    /// Save attachment info to Database
    /// </summary>
    /// <param name="psFileExt"></param>
    /// <param name="psFilename"></param>
    /// <param name="piContentLength"></param>
    private void SaveAttachmentToDatabase(string psFilename,
                                       int piContentLength,
                                        string psMime)
    {
        if (txtAttachment.PostedFile.ContentType.Contains("image/"))
        {
            SavePictureToDatabase(psFilename, piContentLength, psMime);
        }
        else if (txtAttachment.PostedFile.ContentType.Contains("video/"))
        {
            SaveVideoToDatabase(psFilename, piContentLength, psMime);
        }
    }

    /// <summary>
    /// Save attached picture to disk
    /// </summary>
    /// <param name="psFileExt"></param>
    /// <param name="psFilename"></param>
    private void SavePictureToDisk(string psFileExt,
                                   string psFilename)
    {
        string lsServerPath = Server.MapPath("~") + "\\pictures\\" + psFilename + psFileExt;
        txtAttachment.PostedFile.SaveAs(lsServerPath);

        System.Drawing.Image loMyMap = System.Drawing.Image.FromFile(lsServerPath);
        int liWidth = 0, liHeight = 0;
        if (loMyMap.Width > loMyMap.Height)
        {
            liWidth = 150;
            liHeight = Convert.ToInt32(((float)loMyMap.Height / (float)loMyMap.Width) * 150);
        }
        else
        {
            liHeight = 150;
            liWidth = Convert.ToInt32(((float)loMyMap.Width / (float)loMyMap.Height) * 150);
        }
        System.Drawing.Image loThumbnail = loMyMap.GetThumbnailImage(liWidth, liHeight, null, IntPtr.Zero);
        ImageFormat extFormat = ImageFormat.Jpeg;
        switch (psFileExt)
        {
            case ".jpg":
                extFormat = ImageFormat.Jpeg;
                break;
            case ".gif":
                extFormat = ImageFormat.Gif;
                break;
            case ".png":
                extFormat = ImageFormat.Png;
                break;
            case ".bmp":
                extFormat = ImageFormat.Bmp;
                break;
        }
        loThumbnail.Save(Server.MapPath("~") + "/pictures/tn_" + psFilename + psFileExt, extFormat);
        loThumbnail.Dispose();
        loMyMap.Dispose();
    }

    /// <summary>
    /// Save attached video to disk
    /// </summary>
    /// <param name="psFileExt"></param>
    /// <param name="psFilename"></param>
    private void SaveVideoToDisk(string psFileExt,
                                 string psFilename)
    {
        string serverPath = Server.MapPath("~") + "\\videos\\" + psFilename + psFileExt;
        txtAttachment.PostedFile.SaveAs(serverPath);
    }

    /// <summary>
    /// Save Picture and attachment record to Database
    /// </summary>
    /// <param name="psFilename"></param>
    /// <param name="piContentLength"></param>
    private void SavePictureToDatabase(string psFilename,
                                       int piContentLength,
                                       string psMime)
    {
        PictureInfo loRecord = new PictureInfo();
        loRecord.FileName = Utility.ConvertHtmlFilterInput(TextBoxTitle.Text);
        loRecord.Description = Utility.ConvertHtmlFilterInput(TextBoxDescription.Text);
        loRecord.Category = Utility.ConvertHtmlFilterInput(ddlCategory.SelectedValue);
        loRecord.Serverfilename = psFilename;
        loRecord.Uploadtime = DateTime.Now;
        loRecord.Uploader = Convert.ToString(Session["userid"]);
        loRecord.Mimetype = psMime;
        
        PictureInfoManagement.SavePictureInfo(loRecord, "New");
        
        // Put picture in attachments table -----------------------
        Attachment loAttachment = new Attachment();
        loAttachment.PosterID = Convert.ToInt16(Session["userid"]);
        loAttachment.PosterName = Convert.ToString(Session["username"]);
        loAttachment.FileName = "/pictures/" + loRecord.Serverfilename;
        loAttachment.FileSize = piContentLength;
        loAttachment.Comment = loRecord.Description;
        loAttachment.Thumbnail = "/pictures/tn_" + loRecord.Serverfilename;
        AttachmentManagement.SaveAttachment(loAttachment, "New");
    }

    /// <summary>
    /// Save Video and attachment records to Database
    /// </summary>
    /// <param name="psFilename"></param>
    /// <param name="piContentLength"></param>
    private void SaveVideoToDatabase(string psFilename,
                                     int piContentLength,
                                     string psMime)
    {
        VideoInfo loRecord = new VideoInfo();
        loRecord.FileName = Utility.ConvertHtmlFilterInput(TextBoxTitle.Text);
        loRecord.Description = Utility.ConvertHtmlFilterInput(TextBoxDescription.Text);
        loRecord.Category = Utility.ConvertHtmlFilterInput(ddlCategory.SelectedValue);
        loRecord.Serverfilename = psFilename;
        loRecord.Uploadtime = DateTime.Now;
        loRecord.Uploader = Convert.ToString(Session["userid"]);
        loRecord.Mimetype = psMime;
        VideoInfoManagement.SaveVideoInfo(loRecord, "New");
       
        // Put video info in attachments table -----------------------
        Attachment loAttachment = new Attachment();
        loAttachment.PosterID = Convert.ToInt16(Session["userid"]);
        loAttachment.PosterName = Convert.ToString(Session["username"]);
        loAttachment.FileName = "/videos/" + loRecord.Serverfilename;
        loAttachment.FileSize = piContentLength;
        loAttachment.Comment = loRecord.Description;
        loAttachment.Thumbnail = "/videos/VideoNoPreview.jpg";
        AttachmentManagement.SaveAttachment(loAttachment, "New");
    }
}
