using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Commons.Collections;
using NVelocity;
using NVelocity.App;
using NVelocity.Runtime;

namespace WinformDevFramework
{
    public class ServicesCreate
    {
        private static readonly string templateDir = AppDomain.CurrentDomain.BaseDirectory + @"\Template\";
        public bool Create(string tableName, string NameSpace, string outdir)
        {

            VelocityEngine velocityEngine = new VelocityEngine();
            ExtendedProperties props = new ExtendedProperties();
            props.AddProperty(RuntimeConstants.RESOURCE_LOADER, @"file");
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, templateDir);
            props.AddProperty(RuntimeConstants.INPUT_ENCODING, "utf-8");
            props.AddProperty(RuntimeConstants.OUTPUT_ENCODING, "utf-8");
            //模板的缓存设置
            props.AddProperty(RuntimeConstants.FILE_RESOURCE_LOADER_CACHE, true);              //是否缓存
            props.AddProperty("file.resource.loader.modificationCheckInterval", (Int64)30);    //缓存时间(秒)
            velocityEngine.Init(props);
            //为模板变量赋值
            VelocityContext context = new VelocityContext();
            context.Put("tableName", tableName);
            context.Put("NameSpace", NameSpace);
            context.Put("outdir", outdir);
            //从文件中读取模板
            NVelocity.Template template = velocityEngine.GetTemplate(@"\Services.vm");
            if (!Directory.Exists(outdir + "\\Services"))
            {
                Directory.CreateDirectory(outdir + "\\Services");
            }
            //合并模板
            using (StreamWriter writer = new StreamWriter(outdir + $"\\Services\\{tableName.Substring(0,1).ToUpper()}{tableName.Substring(1)}Services.cs", false))
            {
                template.Merge(context, writer);
            }
            return true;
        }
    }
}
