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

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

packageName = "com.lz;"

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)
    new File(dir, className + "Mapper.java").withPrintWriter { out -> generate(out, className, table) }
}

def generate(out, className, table) {
    out.println "package $packageName"
    out.println ""
    out.println "import com.baomidou.mybatisplus.core.mapper.BaseMapper;"
    out.println "import org.apache.ibatis.annotations.Mapper;"
    out.println ""
    out.println "/**"
    out.println " * ${table.getComment() == null ? table.getName() : table.getName() + " (" + table.getComment() + ") "} 固化类"
    out.println " * author: luozhun"
    out.println " * desc 由groovy脚本自动生成"
    out.println " */"
    out.println "@Mapper"
    out.println "public interface ${className}Mapper extends BaseMapper<${className}>{"
    out.println ""
    out.println "}"
}

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]
}