package me.chyxion.tigon.codegen.service.support;

import java.io.File;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.annotation.Order;
import me.chyxion.tigon.codegen.model.CodeGenArgs;
import me.chyxion.tigon.codegen.service.CodeGenerator;

/**
 * @version 0.0.2
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Oct 7, 2014 12:23:13 PM
 */
@Order
public class TableCodeGen extends CodeGenerator {
    private static final Logger log = LoggerFactory.getLogger(TableCodeGen.class);

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean accept(Map<String, Object> dataModel) {
        return (Boolean) dataModel.get("genTable");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String process(Map<String, Object> dataModel, String module, String model) {
        String table = (String) dataModel.get("table");
        log.info("Process generate table [{}] SQL file.", table);
        StringBuilder filePath = new StringBuilder(resourcesDir)
            .append("db/");
        if (StringUtils.isNotBlank(module)) {
            filePath.append(module).append("/");
        }
        filePath.append(table).append(".sql");
        render(new CodeGenArgs(
            CodeGenArgs.TARGET_TABLE, 
            "/codegen/table.ftl", 
            dataModel, 
            filePath.toString()));
                
        if (!Boolean.FALSE.equals(dataModel.get("createTable"))) {
            // ignore drop table error
            try {
                log.info("Execute drop table [{}].", table);
                baseTool.execSQL("drop table " + table);
            }
            catch (Exception e) {
                log.info("Drop table failed, error message [{}], ignore.",
                        e.getMessage());
            }
            // ignore execute sql error
            try {
                log.info("Execute create table SQL file [{}].", filePath);
                baseTool.execSQL(new File(baseTool.getProjDir(), filePath
                        .toString()));
            }
            catch (Exception e) {
                log.warn("Database create table error, ignore.", e);
            }
        }
        return filePath.toString();
    }
}
