using Commons.Collections;
using NVelocity.App;
using NVelocity.Runtime;
using NVelocity;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;

#region << 版 本 注 释 >>
/*--------------------------------------------------------------------
* 版权所有 (c) 2024 WenJY 保留所有权利。
* CLR版本:4.0.30319.42000
* 机器名称:LAPTOP-E0N2L34V
* 命名空间:SlnMesnac.Generate.Templates
* 唯一标识:4acc596a-6223-4156-b16c-952c225eff25
*
* 创建者:WenJY
* 电子邮箱:wenjy@mesnac.com
* 创建时间:2024-04-11 13:27:33
* 版本:V1.0.0
* 描述:
*
*--------------------------------------------------------------------
* 修改人:
* 时间:
* 修改说明:
*
* 版本:V1.0.0
*--------------------------------------------------------------------*/
#endregion << 版 本 注 释 >>
namespace SlnMesnac.Generate.Templates.Service.Impl
{
    public class ServiceCreate
    {
        private static readonly string templateDir = @"F:\桌面\SlnMesnac\SlnMesnac.Generate\Templates\Service\Impl\";

        public bool Create(string tableName, string NameSpace, string outdir)
        {
            try
            {
                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);
                //从文件中读取模板
                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)}ServiceImpl.cs", false))
                {
                    template.Merge(context, writer);
                }
                return true;
            }catch(Exception ex)
            {
                throw new InvalidOperationException($"Service实现类模板创建异常:{ex.Message}");
            }
        }
    }
}