package com.izouma.codegenerator;

import com.izouma.awesomeadmin.model.GenCode;
import org.apache.commons.lang.StringUtils;

import java.io.*;

public class RouterGenerator {

    /**
     * 生成路由
     * @param model
     */
    public static void GenRouter(GenCode model) {
        try {
            File file = new File(model.getRouterPath(), "index.js");
            BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
            StringBuilder routerJs = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                routerJs.append(line).append("\n");
            }
            reader.close();

            int insertLocation = routerJs.indexOf("/**INSERT_LOCATION**/");
            if (insertLocation > -1) {
                String routeName = StringUtils.capitalize(model.getClassName());
                String routePath = StringUtils.uncapitalize(model.getClassName());
                String route = "{\n                    path: '/"
                        + routePath
                        + "',\n                    name: '"
                        + routeName
                        + "',\n                    component: () => import('../pages/"
                        + routeName
                        + "')\n                },\n                {\n                    path: '/"
                        + routePath
                        + "s',\n                    name: '"
                        + routeName
                        + "s',\n                    component: () => import('../pages/"
                        + routeName
                        + "s')\n                }\n                ";
                boolean needComma = !routerJs.toString().substring(0, insertLocation).trim().endsWith(",");
                if (needComma) {
                    routerJs.insert(routerJs.toString().substring(0, insertLocation).lastIndexOf("}") + 1, ",");
                    insertLocation++;
                }
                routerJs.insert(insertLocation, route);
            }

            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(file));
            bufferedOutputStream.write(routerJs.toString().trim().getBytes());
            bufferedOutputStream.close();

            System.out.println("成功生成路由:" + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
