package cn.axzo.workflow.server.conf;

import lombok.AllArgsConstructor;
import org.flowable.spring.SpringProcessEngineConfiguration;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Objects;

import static org.flowable.common.engine.impl.AbstractEngineConfiguration.DB_SCHEMA_UPDATE_FALSE;

/**
 * Ext Database Initializer
 *
 * @author wangli
 * @since 2023/11/18 18:00
 */
@Component
@AllArgsConstructor
public class ExtDatabaseInitializer implements ApplicationRunner {

    private final JdbcTemplate jdbcTemplate;
    private final ResourceLoader resourceLoader;
    private final ApplicationContext applicationContext;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        SpringProcessEngineConfiguration springProcessEngineConfiguration =
                (SpringProcessEngineConfiguration) applicationContext.getBean("springProcessEngineConfiguration");
        if (Objects.equals(DB_SCHEMA_UPDATE_FALSE, springProcessEngineConfiguration.getDatabaseSchemaUpdate())) {
            return;
        }

        if (!isTableExists("EXT_AX_RE_MODEL")) {
            executeSqlScript();
        }

    }

    private boolean isTableExists(String tableName) {
        String query = "SHOW TABLES LIKE '" + tableName + "'";
        return !jdbcTemplate.queryForList(query).isEmpty();
    }

    private void executeSqlScript() {
        Resource resource = resourceLoader.getResource("classpath:sql/bpm-business.sql");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) {
            StringBuilder scriptBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                scriptBuilder.append(line);
            }

            // Split SQL statements and execute each one
            String[] sqlStatements = scriptBuilder.toString().split(";");
            for (String sql : sqlStatements) {
                jdbcTemplate.execute(sql);
            }
        } catch (IOException e) {
            // Handle IOException
            e.printStackTrace();
        }
    }

}
