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.Collections.Generic;
using digioz.VideoModule;
using digioz;
using digioz.admin;
using DexterLib;
using System.Drawing.Imaging;

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

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

    /// <summary>
    /// Menu1_MenuItemClick
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Menu1_MenuItemClick(object sender, MenuEventArgs e)
    {
        txtVideoId.Value = "";
        switch (e.Item.Value)
        {
            case "Videos":
                BindData();
                MultiView1.SetActiveView(Tab1);
                break;
            case "Add":
                SetEditDetails();
                MultiView1.SetActiveView(Tab2);
                break;
        }
    }

    /// <summary>
    /// page
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void page(object sender, DataGridPageChangedEventArgs e)
    {
        videoGrid.CurrentPageIndex = e.NewPageIndex;
        BindData();
    }

    /// <summary>
    /// Image1_Click
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Image1_Click(object sender, ImageClickEventArgs e)
    {

    }
    
    /// <summary>
    /// edit
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void Edit(object s, DataGridCommandEventArgs e)
    {
        txtVideoId.Value = videoGrid.DataKeys[e.Item.ItemIndex].ToString();
        SetEditDetails();
        MultiView1.ActiveViewIndex = 1;
    }

    /// <summary>
    /// Delete
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    public void Delete(object s, DataGridCommandEventArgs e)
    {
        txtVideoId.Value = videoGrid.DataKeys[e.Item.ItemIndex].ToString();
        DeleteVideoFiles(e.Item.Cells[1].Text);
        VideoInfoManagement.DeleteVideoInfo(Convert.ToInt32(txtVideoId.Value));
        BindData();
    }

    /// <summary>
    /// btn_Submit
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        SaveVideoData();
        SetEditDetails();
    }

    /// <summary>
    /// btnPrev_Click
    /// </summary>
    protected void btnPrev_Click(object sender, EventArgs e)
    { 
        FlipVideo("B");
    }

    /// <summary>
    /// btnNext_Click
    /// </summary>
    protected void btnNext_Click(object sender, EventArgs e)
    {
        FlipVideo("F");
    }   

    /// <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 videoGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
    {

        if ((e.Item.ItemType == ListItemType.Item) ||
            (e.Item.ItemType == ListItemType.AlternatingItem))
        {
            ((Image)e.Item.FindControl("Image1")).ImageUrl = GetVideoPreview(Path.GetFileNameWithoutExtension(((VideoInfo)e.Item.DataItem).Serverfilename) + ".jpg");
            Label description = (Label)e.Item.FindControl("Description");
            if (description != null)
            {
                description.Text = Server.HtmlEncode(description.Text);
                // Description is a multi lines text. Encode before displaying
                description.Text = Utility.EncodeNewLine(description.Text);
            }
        }
    }

#region Functions

    private string csServerPath = "";
    private string ServerPath
    {
        get
        {
            if (csServerPath == "")
            {
                csServerPath = Server.MapPath("~") + "\\videos\\";
            }
            return csServerPath;
        }
    }

    /// <summary>
    /// BindData()
    /// </summary>    
    public void BindData()
    {
        int livideoId;
        videoGrid.DataSource = VideoInfoManagement.GetVideoInfoList("");
        videoGrid.DataBind();

        if (!IsPostBack)
        {
            BindLists();
            int.TryParse(Request["VideoId"], out livideoId);
            txtVideoId.Value = livideoId.ToString();
            SetEditDetails();
        }
    }

    /// <summary>
    /// Populates drop down lists and such on first load
    /// </summary>
    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();
    }

    /// <summary>
    /// GetVideoPreview
    /// </summary>
    /// <param name="psFileName"></param>    
    public string GetVideoPreview(string psFileName)
    {
        return "~/videos/" + psFileName + "?n=" + Guid.NewGuid().ToString();
    }

    /// <summary>
    /// GetVideo
    /// </summary>
    /// <param name="psFileName"></param>    
    public string GetVideo()
    {
        string lsPath = "videos/" + txtServerFileName.Value +"?n=" + Guid.NewGuid().ToString();
        return
            "<object classid='CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95' id='objPlayer' width='580' height='450' standby='Loading...'>" +
                "<param name='url' value='" + lsPath + "' />" +
                "<param name='src' value='" + lsPath + "' />" +
                "<param name='autoStart' value='true' />" +
                "<param name='balance' value='0' />" +
                "<param name='currentPosition' value='0' />" +
                "<param name='showControls' value='true' />" +
                "<param name='contextMenu' value='false' />" +
                "<param name='fullScreen' value='true' />" +
                "<param name='mute' value='false' />" +
                "<param name='playCount' value='1' />" +
                "<param name='rate' value='1' />" +
                "<param name='uiMode' value='full' />" +
                "<param name='showDisplay' value='false' />" +
                "<param name='volume' value='50' />" +
            "</object>";
    }

    /// <summary>
    /// SaveVideoData
    /// </summary>
    public void SaveVideoData()
    {
        int liVideoId;
        string lsSaveMode;
        VideoInfo loRecord;
        bool lbRetValue = false;
        string lsMessage;

        if (Page.IsValid)
        {
            int.TryParse(txtVideoId.Value, out liVideoId);
            if (liVideoId > 0)
            {
                loRecord = VideoInfoManagement.GetVideoInfo(liVideoId);
                lsSaveMode = "Update";
            }
            else
            {
                if (!fudVideoFile.HasFile)
                {
                    DisplayMessage("Please select a file to upload", true);
                    return;
                }
                lsSaveMode = "New";
                loRecord = new VideoInfo();
            }
            if (fudVideoFile.HasFile)
            {
                if (!SaveVideo())
                {
                    return;
                }
                loRecord.Serverfilename = txtServerFileName.Value;
                loRecord.Mimetype = fudVideoFile.PostedFile.ContentType;
            }
            loRecord.FileName = Utility.ConvertHtmlFilterInput(txtVideoName.Text);
            loRecord.Description = Utility.ConvertHtmlFilterInput(txtVideoDesc.Text);
            loRecord.Category = Utility.ConvertHtmlFilterInput(ddlCategory.SelectedValue);
            loRecord.Uploadtime = Convert.ToDateTime(txtDateTime.Text);
            loRecord.Uploader = Utility.ConvertHtmlFilterInput(ddlUploader.SelectedValue);

            lbRetValue = VideoInfoManagement.SaveVideoInfo(loRecord, lsSaveMode);
            txtVideoId.Value = loRecord.ID.ToString();
            lsMessage = (lbRetValue
                ? string.Format("Video '{0}' has been sucessfully updated...<br/>",
                                                Server.HtmlEncode(txtVideoName.Text))
                : string.Format("Failed to update Video '{0}'...<br/>",
                                                Server.HtmlEncode(txtVideoName.Text)));
            DisplayMessage(lsMessage, lbRetValue);
        }
        BindData();
    }

    /// <summary>
    /// DeleteVideoFiles
    /// </summary>
    public void DeleteVideoFiles(string psServerFileName)
    {
        File.Delete(ServerPath + psServerFileName);
    }

    /// <summary>
    /// Next and Previous function
    /// </summary>
    /// <param name="loPictureDirection"></param>
    public void FlipVideo(string psDirection)
    {
        int liOldVideoId, liNewVideoId;
        psDirection = (psDirection == "B" ? "B" : "F");
        if (int.TryParse(txtVideoId.Value, out liOldVideoId))
        {
            liNewVideoId = VideoInfoManagement.FlipVideo(liOldVideoId, psDirection, "ALL");
            txtVideoId.Value = liNewVideoId.ToString();
            SetEditDetails();
        }
    }

    /// <summary>
    /// ClearControls
    /// </summary>
    private void ClearControls()
    {
        txtVideoName.Text = "";
        txtVideoDesc.Text = "";
        txtDateTime.Text = "";
        ddlUploader.SelectedValue = "";
        txtServerFileName.Value = "";
        ltPlayer.Text = "";
        ltPlayer.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 video that we are editing
    /// </summary>
    /// <param name="poVideo"></param>
    private void SetEditDetails()
    {
        ListItem loListItem;
        int liPageId = -1;
        string lsPageName = "";
        AdminMenuItem loAdminMenuItem;
        int liVideoId;
        VideoInfo loVideoInfo;

        ClearControls();

        int.TryParse(txtVideoId.Value, out liVideoId);
        if (liVideoId > 0)
        {
            loVideoInfo = VideoInfoManagement.GetVideoInfo(liVideoId);
            txtVideoName.Text = loVideoInfo.FileName;
            txtVideoDesc.Text = loVideoInfo.Description;

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

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

            txtServerFileName.Value = loVideoInfo.Serverfilename;

            ltPlayer.Text = GetVideo();
            ltPlayer.Visible = true;

            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}&VideoId={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(txtVideoId.Value));
    }

    private bool SaveVideo()
    {
        string lsFullPath, lsFilename, lsExt;
        Extensions loExtension = null;

        if (txtServerFileName.Value == "")
        {
            lsFilename = Guid.NewGuid().ToString();
        }
        else
        {
            lsFilename = Path.GetFileNameWithoutExtension(txtServerFileName.Value);
        }

        lsExt = Path.GetExtension(fudVideoFile.PostedFile.FileName.ToLower());

        if (ExtensionsManagement.IsFileValid(lsExt, "VIDEO", out loExtension))
        {
            if (txtServerFileName.Value != "" && txtServerFileName.Value != lsFilename + lsExt)
            {
                DeleteVideoFiles(txtServerFileName.Value);
            }

            lsFullPath = ServerPath + lsFilename + lsExt;

            fudVideoFile.PostedFile.SaveAs(lsFullPath);

            txtServerFileName.Value = lsFilename + lsExt;

            SavePreview();

            return true;
        }
        else
        {
            DisplayMessage("This file format is not currently supported.", true);
            return false;
        }
    }

    private void SavePreview()
    {
        MediaDetClass loMD;
        System.Drawing.Image loImg;
        string lsFilename = Path.GetFileNameWithoutExtension(txtServerFileName.Value);
        string lsBitmap = ServerPath + lsFilename + ".bmp";
        string lsJpeg = ServerPath + lsFilename + ".jpg";
        try
        {
            loMD = new MediaDetClass();
            loMD.Filename = ServerPath + txtServerFileName.Value;
            loMD.CurrentStream = 0;
            loMD.WriteBitmapBits(0, 150, 150, lsBitmap);

            loImg = System.Drawing.Image.FromFile(lsBitmap);
            loImg.Save(lsJpeg, ImageFormat.Jpeg);
            loImg.Dispose();
            File.Delete(lsBitmap);
        }
        catch
        {
            File.Copy(ServerPath + "VideoNoPreview.jpg", lsJpeg);
        }
    }

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

#endregion
}
