import com.intellij.database.model.DasTable
import com.intellij.database.util.Case
import com.intellij.database.util.DasUtil

/*
 * Available context bindings:
 *   SELECTION   Iterable<DasObject>
 *   PROJECT     project
 *   FILES       files helper
 */

packageName = "com.lz;"

typeMapping = [
        (~/(?i)multipoint/)               : "MultiPoint",
        (~/(?i)multilinestring/)          : "MultiLineString",
        (~/(?i)multipolygon/)             : "MultiPolygon",
        (~/(?i)point/)                    : "Point",
        (~/(?i)linestring/)               : "LineString",
        (~/(?i)polygon/)                  : "Polygon",
        (~/(?i)bigint/)                   : "Long",
        (~/(?i)int/)                      : "Integer",
        (~/(?i)float|double|decimal|real/): "java.math.BigDecimal",
        (~/(?i)varchar/)                  : "String",
        (~/(?i)CHAR(1)/)                  : "String",
        (~/(?i)datetime/)                 : "java.time.LocalDateTime",
        (~/(?i)time/)                     : "java.time.LocalTime",
        (~/(?i)date/)                     : "java.time.LocalDate",
        (~/(?i)/)                         : "String",
]

ignoreFeilds = ["id", "snowFlakeId", "deleteFlag", "createBy", "updateBy", "createTime", "updateTime"]

FILES.chooseDirectoryAndSave("Choose directory", "Choose where to store generated files") { dir ->
    SELECTION.filter { it instanceof DasTable }.each { generate(it, dir) }
}

def generate(table, dir) {
    def className = javaName(table.getName(), true)
    def fields = calcFields(table)
    new File(dir, className + ".java").withPrintWriter { out -> generate(out, className, fields, table) }
}

def generate(out, className, fields, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import java.io.Serial;"
    out.println "import java.io.Serializable;"
    out.println ""
    out.println "import lombok.Data;"
    out.println "import lombok.AllArgsConstructor;"
    out.println "import lombok.NoArgsConstructor;"
    out.println "import lombok.experimental.SuperBuilder;"
    out.println "import lombok.EqualsAndHashCode;"
    out.println "import com.baomidou.mybatisplus.annotation.TableName;"
    out.println ""
    out.println ""
    out.println "/**"
    out.println " * ${table.getComment() == null ? table.getName() : table.getComment()} 实体类"
    out.println " * author: luozhun"
    out.println " * desc 由groovy脚本自动生成"
    out.println " */"
    out.println "@Data"
    out.println "@AllArgsConstructor"
    out.println "@NoArgsConstructor"
    out.println "@SuperBuilder"
    out.println "@EqualsAndHashCode(callSuper = true)"
    out.println "@TableName(autoResultMap = true)"
    out.println "public class $className extends BaseEntity implements Serializable {"
    out.println ""
    out.println "\t@Serial"
    out.println genSerialID()
    out.println ""
    fields.each() {
        if (ignoreFeilds.contains(it.name)) return true
        if (it.comment == null) it.comment = it.name
        out.println "    /**"
        out.println "     * ${it.comment}"
        out.println "     */"
        out.println "    private ${it.type} ${it.name};"
        out.println ""
    }
    out.println ""
    out.println "}"
}

def calcFields(table) {
    DasUtil.getColumns(table).reduce([]) { fields, col ->
        def spec = Case.LOWER.apply(col.getDataType().getSpecification())
        def typeStr = typeMapping.find { p, t -> p.matcher(spec).find() }.value
        fields += [[
                           name   : javaName(col.getName(), false),
                           type   : typeStr,
                           comment: col.getComment()
                   ]]
    }
}

def javaName(str, capitalize) {
    def s = com.intellij.psi.codeStyle.NameUtil.splitNameIntoWords(str)
            .collect { Case.LOWER.apply(it).capitalize() }
            .join("")
            .replaceAll(/[^\p{javaJavaIdentifierPart}[_]]/, "_")
    capitalize || s.length() == 1 ? s : Case.LOWER.apply(s[0]) + s[1..-1]
}

static String genSerialID() {
    return "\tprivate static final long serialVersionUID =  1L;"
}

/**
 * 解析common 例如 删除标记(1:已删除,2:未删除)
 * 则解析后为 描述:删除标记 规则:1:已删除,2:未删除
 */
static String analysisComment(comment) {
    def regex = ~/(.*)[\(|\[|\{|\（|\<](.*)[\)|\]|\}|\）|\>]/
    def matcher = regex.matcher(comment)
    if (matcher) {
        def result = matcher[0]
        def explain = result[1]
        def rule = result[2]
        return "    @Comment(explain = \"$explain\", rule = \"$rule\")"
    } else {
        return "    @Comment(explain = \"${comment}\")"
    }
}