<%-- 
Author: yubaolee
Description: 用于生成OpenAuth.WebApi接口相关代码，包括controller/app/实体/dbcontext
--%>
<%@ Template Language="C#" TargetLanguage="Text" Debug="True" OutputType="Normal"  %>

<%@ Assembly Name="SchemaExplorer" %>
<%@ Assembly Name="CodeSmith.CustomProperties" %>

<%@ Assembly Name="Mono.Cecil" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory" Path="..\Common" %>
<%@ Assembly Name="ICSharpCode.NRefactory.CSharp" Path="..\Common" %>

<%@ Assembly Src="Internal\Model.cs" %>
<%@ Assembly Src="Internal\Extensions.cs" %>
<%@ Assembly Src="Internal\Generator.cs" %>
<%@ Assembly Src="Internal\Parser.cs" %>

<%@ Import Namespace="System.Collections.Generic" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Linq" %>
<%@ Import Namespace="System.Text" %>
<%@ Import Namespace="System.Text.RegularExpressions" %>
<%@ Import Namespace="System.Diagnostics" %>

<%@ Import Namespace="SchemaMapper" %>

<%@ Property Name="WholeDb" 
Type="System.Boolean" 
Category="1.Database"
Default="true"
Description="是否直接生成选定数据库中的所有表" %>

<%@ Property Name="HeaderModel" 
Type="System.Boolean" 
Category="1.Database"
Default="true"
Description="是否为启用头表模式，即类似‘入库订单’界面" %>

<%@ Property Name="SourceDatabase"
    Type="SchemaExplorer.DatabaseSchema"
    Category="1.Database"
    Description="The source database." %>

<%@ Property Name="SourceTables" 
Type="SchemaExplorer.TableSchemaCollection" 
Category="1.Database" Description="可以选择一个或多个表（使用Ctrl键）" %>

<%@ Property Name="directory"
             Type="System.String"
             Default=".\"
             Optional="True"
             Description="代码生成路径"
             Editor="System.Windows.Forms.Design.FolderNameEditor, System.Design, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" %>
             
<%@ Property Name="ContextNamespace"
             Type="System.String"
             Category="2.Class"
             Default="OpenAuth.Repository"
             OnChanged="OnContextNamespaceChanged"
             Description="DbContext默认命名空间，尽量不要更改"%>
<%@ Property Name="EntityNamespace"
             Type="System.String"
             Default="OpenAuth.Repository.Domain"
             Category="2.Class"
             Description="实体默认命名空间，尽量不要更改"%>
             

<%@ Register Name="EntityGeneratedClass"
             Template="Internal\Entity.Generated.cst"
             MergeProperties="False" %>
             
<%@ Register Name="ContextGeneratedClass"
             Template="Internal\Context.Generated.cst"
             MergeProperties="True" %>
             
<%@ Register Name="ApplicationGenerateClass"
             Template="ApiGenerate\Application.cst"
             MergeProperties="False" %>
<%@ Register Name="RequestGenerateClass"
             Template="ApiGenerate\Request.cst"
             MergeProperties="False" %>
<%@ Register Name="ModifyReqGenerateClass"
             Template="ApiGenerate\ModifyReq.cst"
             MergeProperties="False" %>
<%@ Register Name="ControllerGenerateClass"
             Template="ApiGenerate\Controller.cst"
             MergeProperties="False" %>
             
开始创建OpenAuth.Core WebApi相关代码 ...
<% Generate(); %>

<script runat="template">
   private TableSchemaCollection tables;
   public void  Generate()
    {
        Stopwatch watch = Stopwatch.StartNew();
        string outputDirectory = Path.GetFullPath(directory);

        if(WholeDb){
            tables = SourceDatabase.Tables;
        }
        else{
            tables = SourceTables;
        }

        CreateEntityClasses();
         CreateControllerClass();
         CreateApplicationClass();
         CreateReqClass();
         CreateContextClass();
        
        watch.Stop();
        Response.WriteLine("Generate Time: " + watch.ElapsedMilliseconds + " ms");
    }
    
    //创建实体类
    public void CreateEntityClasses()
    {
        EntityGeneratedClass generatedClass = this.Create<EntityGeneratedClass>();
        this.CopyPropertiesTo(generatedClass);

        foreach(TableSchema table in tables)
        {
            string className = table.Name;
            string generatedFile =  Path.GetFullPath(directory) + "OpenAuth.Repository\\Domain\\" + className + ".cs";

            generatedClass.Table = table;
            Response.WriteLine("已生成"+generatedFile);
            generatedClass.RenderToFile(generatedFile, generatedFile, true);
        }

    }

    //创建DbContext
    public void CreateContextClass()
    {
        ContextGeneratedClass generatedClass = this.Create<ContextGeneratedClass>();
        this.CopyPropertiesTo(generatedClass);

        string dbContextName;
        if(WholeDb){
          dbContextName = SourceDatabase.Name.ToSafeName();
        }
        else{
            dbContextName = SourceTables.First().Database.Name.ToSafeName();
         }
        dbContextName = StringUtil.ToPascalCase(dbContextName);

        string generatedFile = "OpenAuth.Repository\\" + dbContextName + "Context.cs";
       
        Response.WriteLine("重要提示!!!!把下面内容添加到"+generatedFile+"对应的位置中，千万不要直接覆盖！！！");
        Response.WriteLine(generatedClass.RenderToString());
    }
    

    //创建控制器,如UserManagerController.cs
    public void CreateControllerClass()
    {
        ControllerGenerateClass generatedClass = this.Create<ControllerGenerateClass>();
        this.CopyPropertiesTo(generatedClass);


         foreach(TableSchema table in tables)
        {
             string generatedFile = Path.GetFullPath(directory) + "OpenAuth.WebApi\\Controllers\\"+  table.Name + "sController.cs";

            generatedClass.ModuleName = table.Name;

            Response.WriteLine("已生成"+generatedFile);
            generatedClass.RenderToFile(generatedFile, generatedFile, true);
        }
    }

    //创建APP层,如UserManagerApp.cs
    public void CreateApplicationClass()
    {
        ApplicationGenerateClass generatedClass = this.Create<ApplicationGenerateClass>();
        this.CopyPropertiesTo(generatedClass);

        foreach(TableSchema table in tables)
        {
            string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\"+ table.Name +"\\"+  table.Name + "App.cs";
            generatedClass.Table = table;
            //generatedClass.Entity = entity;
            Response.WriteLine("已生成"+generatedFile);
            generatedClass.RenderToFile(generatedFile, generatedFile, true);
        }
    }
    
    
    //创建请求参数,如QueryUserListReq.cs
    public void CreateReqClass()
    {
        RequestGenerateClass generatedClass = this.Create<RequestGenerateClass>();
        this.CopyPropertiesTo(generatedClass);
         foreach(TableSchema table in tables)
        {
            string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\"+ table.Name +"\\Request\\Query"+   table.Name + "ListReq.cs";
            generatedClass.ModuleName =  table.Name;
            Response.WriteLine("已生成"+generatedFile);
            generatedClass.RenderToFile(generatedFile, generatedFile, true);
        }
        
        //生成编辑修改的请求参数
        ModifyReqGenerateClass modifyReqGenerateClass = this.Create<ModifyReqGenerateClass>();
        this.CopyPropertiesTo(modifyReqGenerateClass);
         foreach(TableSchema table in tables)
        {
            string generatedFile = Path.GetFullPath(directory) + "OpenAuth.App\\"+ table.Name +"\\Request\\AddOrUpdate"+   table.Name + "Req.cs";
            modifyReqGenerateClass.Table = table;
            Response.WriteLine("已生成"+generatedFile);
            modifyReqGenerateClass.RenderToFile(generatedFile, generatedFile, true);
        }
    }

    private void OnContextNamespaceChanged(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(ContextNamespace))
            return;

        if (string.IsNullOrEmpty(EntityNamespace))
            EntityNamespace = ContextNamespace + ".Domain";
    }

</script>