package com.gitee.gen.util;

import com.gitee.gen.entity.TemplateConfig;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 模板元信息工具类
 */
public final class TemplateMetaUtils {

    private TemplateMetaUtils() {
    }

    /**
     * 解析模板内容中的元信息
     */
    public static Map<String, String> parseMetaContent(String content) {
        content = StringUtil.trimLeadingWhitespace(content);
        if (content != null && content.startsWith("##")) {
            int rowIdx = content.indexOf('\n');
            String metaInfo = content.substring(2, rowIdx);
            return parseMetaRow(metaInfo);
        }
        return Collections.emptyMap();
    }

    /**
     * 解析元数据信息
     */
    public static Map<String, String> parseMetaRow(String row) {
        char[] charArray = row.toCharArray();

        Map<String, String> data = new HashMap<>();

        StringBuilder kvBuilder = new StringBuilder();
        // 剩余未闭合表达式数量
        int leftExpr = 0;
        for (int i = 0, len = charArray.length, end = len - 1; i < len; i++) {
            char c = charArray[i];
            boolean kvEnd = false;
            if (i == end) {
                kvBuilder.append(c);
                kvEnd = true;
            } else if (',' == c && leftExpr == 0) {
                kvEnd = true;
            }

            if (kvEnd) {
                String[] kv = kvBuilder.toString().trim().split("=");
                data.put(kv[0].trim(), kv.length == 1 ? null : kv[1].trim());
                kvBuilder = new StringBuilder();
                continue;
            }

            kvBuilder.append(c);
            switch (c) {
                case '{':
                case '(':
                    leftExpr++;
                    break;
                case '}':
                case ')':
                    leftExpr--;
                    break;
                default:
                    break;
            }
        }
        if (leftExpr > 0) {
            throw new RuntimeException("读取元数据失败,有" + leftExpr + "个表达式未闭合");
        }
        return data;
    }

    /**
     * 生成元数据的模板内容
     */
    public static String generateMetaContent(TemplateConfig template) {
        String content = StringUtil.trimLeadingWhitespace(template.getContent());
        String metaRow = generateMetaRow(template);
        if (content.startsWith("##")) {
            int rowIdx = content.indexOf('\n');
            if(rowIdx == -1) {
                content = metaRow;
            } else {
                content = metaRow + content.substring(rowIdx);
            }
        } else {
            content = metaRow + "\n" + content;
        }
        return content;
    }

    /**
     * 解析元数据信息
     */
    public static String generateMetaRow(TemplateConfig template) {
        String format = "## filename=%s, folder=%s";
        String filename = template.getFileName() != null ? template.getFileName() : "";
        String folder = template.getFolder() != null ? template.getFolder() : "";
        return String.format(format, filename, folder);
    }
}
