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

namespace ynhtm.Admin
{
    using Common;
    using DBUtility;

    public partial class Database : System.Web.UI.Page
    {
        void PageBind()
        {
            using (var db = DbBase.GetDb())
            {
                this.lblName.Text = db.Name.HtmlEncode();
                this.lblSize.Text = db.Size;
                this.lblVersion.Text = db.Version;
            }
            var dir = new DirectoryInfo(this.MapPath("~/Backup/"));
            if (dir.Exists) this.rptList.DataSource = dir.GetFiles().OrderByDescending(i => i.CreationTime);
            this.rptList.DataBind();
        }

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

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                if (this.Request["Action"] == "Down")
                {
                    var fileName = this.Request["FileName"];
                    this.Response.Clear();
                    this.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName.UrlEncode());
                    this.Response.WriteFile(this.MapPath("~/Backup/" + fileName));
                }
                else
                    this.PageBind();
            }
        }

        protected void rptList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "Del")
            {
                File.Delete(this.MapPath("~/Backup/" + e.CommandArgument.ToString()));
                this.PageBind();
                this.ShowInfo("删除数据备份文件成功");
            }
        }

        protected void btnBackup_Click(object sender, EventArgs e)
        {
            var dir = new DirectoryInfo(this.MapPath("~/Backup"));
            dir.Create();
            using (var db = DbBase.GetDb())
                db.Backup(dir.FullName + "\\ynhtm_" + DateTime.Now.ToString("yyyMMddHHmmss") + ".bak");
            this.PageBind();
            this.ShowInfo("备份数据库成功");
        }

        protected void btnSQL_Click(object sender, EventArgs e)
        {
#if DEMO
            this.ShowAlert("演示版无法执行");
            return;
#endif
            using (var db = DbBase.GetDb())
            {
                var result = db.ExecuteNonQuery(this.txtSQL.Text);
                this.ShowInfo("SQL 执行成功，受影响行数(" + result + ")");
            }
        }
    }
}