using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;

namespace ynhtm.Admin
{
    using Common;

    public partial class ThemeEdit : System.Web.UI.Page
    {
        void PageBind()
        {
            var dir = new DirectoryInfo(this.Server.MapPath("~/Theme/" + this.Request["Path"]));
            this.rptList.DataSource = dir.GetFiles().Where(i => Regex.IsMatch(i.Extension, @"\.(htm|html|css|txt|xml|cshtml|vbhtml)$", RegexOptions.Compiled | RegexOptions.IgnoreCase));
            this.rptList.DataBind();
        }

        void EditFile(string fileName)
        {
            var s = "/Theme/" + this.Request["Path"] + "/" + fileName;
            var path = this.Server.MapPath("~/" + s);
            using (var reader = new StreamReader(path, Encoding.Default, true))
                this.txtContent.Text = reader.ReadToEnd();
            this.lblPath.Text = s.HtmlEncode();
            this.ViewState["Path"] = path;
            this.btnSave.Enabled = true;
        }

        protected string EvalLength
        {
            get { return Utils.GetFileSize(this.Eval<long>("Length")); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.lblTitle.Text = "编辑主题(" + this.Request["Path"].HtmlEncode() + ")";
            this.Form.DefaultButton = this.btnSave.UniqueID;
            if (!this.IsPostBack)
            {
                this.PageBind();
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
#if DEMO
            this.ShowAlert("演示版无法修改");
            return;
#endif
            File.WriteAllText(this.ViewState["Path"].ToString(), this.txtContent.Text, Encoding.UTF8);
            this.ShowInfo("保存文件成功");
        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            if (this.IsValid)
            {
                var path = this.Server.MapPath("~/Theme/" + this.Request["Path"] + "/" + this.txtName.Text);
                if (!File.Exists(path))
                {
                    File.WriteAllText(path, this.txtContent.Text, Encoding.UTF8);
                    this.txtName.Text = "";
                    this.PageBind();
                    this.ShowInfo("新建文件成功");
                }
                else
                    this.ShowAlert("已存在相同文件");
            }
        }

        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Edit")
                this.EditFile(e.CommandArgument.ToString());
            else if (e.CommandName == "Del")
            {
#if DEMO
                this.ShowAlert("演示版无法操作");
                return;
#endif
                File.Delete(this.Server.MapPath("~/Theme/" + this.Request["Path"] + "/" + e.CommandArgument));
                this.PageBind();
                this.ShowInfo("删除文件成功");
            }
        }
    }
}