using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
namespace Mammonth.Common {
    public class Template {

        protected static string strError;

        public static string GetLastError() {
            return strError;
        }

        /// <summary>
        /// 创建静态数据JSON文本文件
        /// </summary>
        /// <param name="templateContext"></param>
        /// <param name="outFilePath"></param>
        /// <returns></returns>
        /// <remarks>
        /// creater: zhao
        /// </remarks>
        public static bool CreateJSON(string templateContext, string outFilePath) {
            return CreateHTML(templateContext, outFilePath);
        }

        /// <summary>
        /// 获取模板内容
        /// </summary>
        /// <param name="tempPath">模板路径</param>
        /// <returns></returns>
        public static string ReadJSON(string tempPath) {
            return ReadTemplate(tempPath);
        }
        /// <summary>
        /// 获取模板内容
        /// </summary>
        /// <param name="tempPath">模板路径</param>
        /// <returns></returns>
        public static string ReadTemplate(string tempPath) {
            if (System.IO.File.Exists(tempPath)) {
                //string ModelTemp = HttpContext.Current.Server.MapPath(tempPath);  // 读取模板文件       
                string str = "";
                Encoding encoding = Encoding.GetEncoding("utf-8");//gb2312
                StreamReader sr = null; try {
                    sr = new StreamReader(tempPath, encoding);
                    str = sr.ReadToEnd(); // 读取文件  
                } catch //(Exception exp)
                {
                    //HttpContext.Current.Response.Write(exp.Message);
                    //HttpContext.Current.Response.End(); sr.Close();
                } finally {
                    sr.Close();
                }
                return str;
            } else {

                return "";
            }
        }

        /// <summary>
        /// 遍历一个实体对象的属性并取出属性值填充模板标签
        /// </summary>
        /// <param name="tempContext">模板内容</param>
        /// <param name="model">数据实体对象</param>
        /// <param name="type">数据实体类的类型</param>
        /// <param name="format">格式化字符串</param>
        /// <returns></returns>
        public static string AccessProperty(string tempContext, object model, Type type, string format) {
            //使用反射替换所有属性值(不考虑继承的属性值)
            PropertyInfo[] pinfos = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
            for (int i = 0; i < pinfos.Length; i++) {
                string strtype = pinfos[i].PropertyType.ToString();
                object value = pinfos[i].GetValue(model, null);
                string strvalue = (value != null) ? value.ToString() : "";
                //替换自定义标签为内容
                switch (strtype) {
                    case "System.Nullable`1[System.DateTime]":
                        strvalue = strvalue.Replace(" 0:00:00", "");
                        break;
                    case "System.Nullable`1[System.Boolean]":
                        if (strvalue == "True") {
                            strvalue = "√";
                        }
                        break;
                    default:

                        break;
                }
                tempContext = tempContext.Replace(string.Format(format, pinfos[i].Name), strvalue);
            }
            return tempContext;
        }


        /// <summary>
        /// 创建静态预览HTML文件
        /// </summary>     
        /// <param name="templateContext">模板表现形式</param>
        /// <param name="outFilePath">保存路径</param>
        /// <param name="append">是否追加文本 默认false表示不追加</param>
        /// <returns></returns>
        /// <remarks>
        /// creater: zhao        
        /// </remarks>
        public static bool CreateHTML(string templateContext, string outFilePath ,bool append = false ) {
            //数据与表现形式
            string OutPutPath = "";
            OutPutPath = outFilePath;
            //OutPutPath = HttpContext.Current.Server.MapPath(outFilePath); //html存放地址        
            Encoding encoding = Encoding.GetEncoding("utf-8");//
            StreamWriter sw = null;
            try {
                //string outpath = HttpContext.Current.Server.MapPath(outFilePath.Remove(outFilePath.LastIndexOf('/')));
                //if (!Directory.Exists(outpath))
                //    Directory.CreateDirectory(outpath);
                //if (System.IO.File.Exists(OutPutPath)) {
                //    System.IO.File.Delete(OutPutPath);
                //}
                sw = new StreamWriter(OutPutPath, append, encoding);//文件不存在就创建,append,false表示不追加
                sw.Write(templateContext);
                sw.Flush();
                //
                sw.Close();
                return true;
            } catch (Exception ex) {
                //HttpContext.Current.Response.Write(ex.Message);
                //HttpContext.Current.Response.End();
                strError = ex.Message;
                return false;
            } finally {
                if (sw != null)
                    sw = null;
            }
        }


        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="DirectoryPath">物理路径</param>
        /// <returns></returns>
        /// <example> 这是一个例子显示如何调用此方法
        ///     <code></code>
        /// </example>
        /// <remarks> 
        /// 调用页面： 
        /// 创建人及日期：ZhaoShunLu 2013-9-16
        /// <para>修改人、日期及内容:</para>
        /// </remarks>
        public static bool DeleteDirectory(string DirectoryPath) {
            if (System.IO.Directory.Exists(DirectoryPath)) {
                try {
                    System.IO.Directory.Delete(DirectoryPath, true);
                    return true;
                } catch// (System.Exception ex)
                {
                    return false;
                }

            } else
                return false;
        }

        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="DirectoryPath">物理路径</param>
        /// <param name="OnlyEmpty">OnelyEmpty=true 只有空文件夹才删除 否则不做判断</param>
        /// <returns></returns>
        /// <remarks> 
        /// 调用页面： 
        /// 创建人及日期：ZhaoShunLu 2013-9-16
        /// <para>修改人、日期及内容:</para>
        /// </remarks>
        public static bool DeleteDirectory(string DirectoryPath, bool OnelyEmpty) {
            if (System.IO.Directory.Exists(DirectoryPath)) {
                try {
                    //判断是否非空
                    if (OnelyEmpty) {
                        System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(DirectoryPath);
                        if (di.GetFiles().Length == 0 && di.GetDirectories().Length == 0) {
                            //目录为空才删除
                            System.IO.Directory.Delete(DirectoryPath, true);
                            return true;
                        } else {
                            return false;
                        }
                    } else {
                        //直接删除
                        System.IO.Directory.Delete(DirectoryPath, true);
                        return true;
                    }

                } catch// (System.Exception ex)
                {
                    return false;
                }

            } else
                return false;

        }
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="FilePath">物理路径</param>
        /// <returns></returns>
        /// <example> 这是一个例子显示如何调用此方法
        ///     <code></code>
        /// </example>
        /// <remarks> 
        /// 调用页面： 
        /// 创建人及日期：ZhaoShunLu 2013-9-16
        /// <para>修改人、日期及内容:</para>
        /// </remarks>
        public static bool DeleteFile(string FilePath) {
            if (System.IO.File.Exists(FilePath)) {
                try {
                    System.IO.File.Delete(FilePath);
                    return true;
                } catch// (System.Exception ex)
                {
                    return false;
                }

            } else
                return false;

        }
    }
}
