using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;

namespace ASPNetPortal
{
    /// <summary>
    /// Summary description for EditTextModule.
    /// </summary>
    public class EditTextModule : System.Web.UI.Page
    {
        protected System.Web.UI.WebControls.TextBox Src;
        protected System.Web.UI.WebControls.TextBox DesktopText;
        protected System.Web.UI.WebControls.TextBox MobileSummary;
        protected System.Web.UI.WebControls.TextBox MobileDetails;
        protected System.Web.UI.WebControls.LinkButton updateButton;
        protected System.Web.UI.WebControls.LinkButton cancelButton;
    
        int moduleId = 0;

        //****************************************************************
        //
        // The Page_Load event on this Page is used to obtain the ModuleId
        // of the module to edit.
        //
        // It then uses the data component
        // to populate the page's edit controls with the text details.
        //
        //****************************************************************
        private void Page_Load(object sender, System.EventArgs e)
        {
            // Determine ModuleId 
            moduleId = Int32.Parse(Request.Params["Mid"]);
            string TextToHtmlCode;

            // Verify that the current user has access to edit this module
            if (PortalSecurity.HasEditPermissions(moduleId) == false) 
            {
                Response.Redirect("~/Admin/EditAccessDenied.aspx");
            }

            if (Page.IsPostBack == false) 
            {
                if (moduleId > 0) 
                {

                    Hashtable settings;
                
                    // Get settings from the database
                    settings = PortalSettings.GetModuleSettings(moduleId);
                    String TextSrc = (String) settings["TextSrc"];

                    if ((TextSrc != null) && (TextSrc != "")) 
                    {
                        if  (File.Exists(Server.MapPath(TextSrc))) 
                        {
                            // Open the txt file 
                            string FileName =  Server.MapPath(TextSrc);
                            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

                            // Read txt file to the end
                            StreamReader r = new StreamReader(fs);
                            TextToHtmlCode = r.ReadToEnd();

                            // 
                            r.Close();
                            fs.Close();

                            if ((TextToHtmlCode != null) && (TextToHtmlCode != ""))
                            {
                                // get the file location
                                Src.Text = TextSrc.ToString();
                                // Display the text from the stream
                                DesktopText.Text = TextToHtmlCode;
                            }
                            else
                            {
                                Src.Text = "Todo: Add Content...";
                                DesktopText.Text = "Todo: Add Content...";
                                MobileSummary.Text = "Todo: Add Content...";
                                MobileDetails.Text = "Todo: Add Content...";
                            }
                        }
                        else 
                        {
                            Controls.Add(new LiteralControl("<" + "br" + "><" + "span class=NormalRed" + ">" + "File " + TextSrc + " not found.<" + "br" + ">"));
                        }
                    }
                }

                // Store URL Referrer to return to portal
                ViewState["UrlReferrer"] = Request.UrlReferrer.ToString();
            }    

        }
        
        //****************************************************************
        //
        // The CancelBtn_Click event handler on this Page is used to cancel
        // out of the page, and return the user back to the portal home
        // page.
        //
        //****************************************************************
        private void cancelButton_Click(object sender, System.EventArgs e)
        {
            // Redirect back to the portal home page
            Response.Redirect((String) ViewState["UrlReferrer"]);
        }
        
        //****************************************************************
        //
        // The UpdateBtn_Click event handler on this Page is used to save
        // the text changes to the text file and text file link to the database.
        //
        //****************************************************************
        private void updateButton_Click(object sender, System.EventArgs e)
        {
            // First Update the settings for a Text File path in the database
            // this update happens in ModuleSettings Table
            AdminDB admin = new AdminDB();
            string TextSrc = Src.Text;
            admin.UpdateModuleSetting(moduleId, "TextSrc", TextSrc);

            string TextToHtmlCode = DesktopText.Text; 

            // Second get the text file path and update the text file 
            if ((TextSrc != null) && (TextSrc != "")) 
            {
                string FilePath = Server.MapPath(TextSrc);
                string FileName =  FilePath;

                // if file exists append to it
                if  (File.Exists(FilePath)) 
                {
                    
                    // Delete the file if it exists.
                    if (File.Exists(FilePath)) 
                    {
                        File.Delete(FilePath);
                    }
                    
                    // create the new file
                    FileStream fs = new FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
                    StreamWriter w = new StreamWriter(fs);
                    w.BaseStream.Seek(0, SeekOrigin.End);

                    if ((TextToHtmlCode != null) && (TextToHtmlCode != ""))
                    {
                        w.WriteLine("{0}", TextToHtmlCode);
                        w.Flush();
                        w.Close();
                        fs.Close();
                    }
                    else
                    {
                        w.WriteLine("{0}", "Todo: Add Content...");
                        w.Flush();
                        w.Close();
                        fs.Close();
                            
                    }
                }
            }
            else
            {
                Controls.Add(new LiteralControl("<" + "br" + "><" + "span class=NormalRed" + ">" + "File " + TextSrc + " not found.<" + "br" + ">"));
            }


            // Redirect back to the portal home page
            Response.Redirect((String) ViewState["UrlReferrer"]);

        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }
        
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {    
            this.updateButton.Click += new System.EventHandler(this.updateButton_Click);
            this.cancelButton.Click += new System.EventHandler(this.cancelButton_Click);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion


    }
}