package com.dsideal;

import Plugin.LogBackLogFactory;
import com.dsideal.sso.Controller.AppLoginController;
import com.dsideal.sso.Controller.IndexController;
import com.dsideal.sso.Interceptor.EmptyInterceptor;
import com.jfinal.config.*;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.dialect.PostgreSqlDialect;
import com.jfinal.plugin.hikaricp.HikariCpPlugin;
import com.jfinal.plugin.redis.RedisPlugin;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.template.Engine;
import com.dsideal.sso.Controller.CommomController;
import com.dsideal.sso.Controller.WebLoginController;
import com.dsideal.sso.Util.CommonUtil;

import java.io.File;

public class Start extends JFinalConfig {

    public static void main(String[] args) {
        UndertowServer.create(Start.class, "undertow.properties").start();
    }

    //在jfinal启动完成后马上执行
    public void onStart() {
        //打印 启动Logo
        String path = Start.class.getClassLoader().getResource("Logo.txt").getPath();
        File file = new File(path);
        System.out.println(CommonUtil.txt2String(file));
    }

    /**
     * 配置常量
     */
    public void configConstant(Constants me) {
        //配置日志框架logback
        me.setLogFactory(new LogBackLogFactory());
        PropKit.use("application.properties");
      }

    /**
     * 配置路由
     */
    public void configRoute(Routes me) {
        me.add("/", IndexController.class);
        me.add("/web", WebLoginController.class);
        me.add("/common", CommomController.class);
        me.add("/app", AppLoginController.class);
    }

    public void configEngine(Engine me) {
    }

    /**
     * 配置插件
     */
    public void configPlugin(Plugins me) {
        HikariCpPlugin hp = new HikariCpPlugin(PropKit.get("jdbcUrl"), PropKit.get("user"),
                PropKit.get("password").trim(), PropKit.get("driverClassName"));
        me.add(hp);
        // 配置ActiveRecord插件
        ActiveRecordPlugin arp = new ActiveRecordPlugin(hp);
        arp.setDialect(new PostgreSqlDialect());
        String basePath = Start.class.getClassLoader().getResource(".").getPath();
        File sqlDir = new File(basePath + "/Sql");
        File[] sqlFiles = sqlDir.listFiles();
        if (sqlFiles != null) {
            for (File sqlFile : sqlFiles) {
                //只加载.sql文件
                if (sqlFile.getName().indexOf(".sql") > 0) {
                    arp.addSqlTemplate("/Sql/" + sqlFile.getName());
                }
            }
        }
        //加载
        me.add(arp);
        RedisPlugin redis = new RedisPlugin("Redis", PropKit.get("redis_ip"), PropKit.getInt("redis_port"), 10000);
        me.add(redis);
    }


    /**
     * 配置全局拦截器
     */
    public void configInterceptor(Interceptors me) {
        //注册非空拦截器
        me.add(new EmptyInterceptor());
    }

    /**
     * 配置处理器
     */
    public void configHandler(Handlers me) {

    }
}
