package com.tongtech.tfw.workflow.config;

import com.tongtech.tfw.backend.core.models.exceptions.FrameworkException;
import javax.sql.DataSource;
import liquibase.Liquibase;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.database.DatabaseFactory;
import liquibase.database.jvm.JdbcConnection;
import liquibase.exception.DatabaseException;
import liquibase.resource.ClassLoaderResourceAccessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class DatabaseAutoConfiguration {
    private static final Logger log = LoggerFactory.getLogger(DatabaseAutoConfiguration.class);
    protected static final String LIQUIBASE_CHANGELOG_PREFIX = "ACT_DE_";

    @Value("${spring.profiles.active}")
    private String activeProfile;


    public DatabaseAutoConfiguration() {
    }

    @Bean
    public Liquibase liquibase(DataSource dataSource) {
        log.info("Configuring Liquibase");
        Liquibase liquibase = null;


        Liquibase var5;
        try {
            DatabaseConnection connection = new JdbcConnection(dataSource.getConnection());
            Database database = DatabaseFactory.getInstance().findCorrectDatabaseImplementation(connection);
            database.setDatabaseChangeLogTableName("ACT_DE_" + database.getDatabaseChangeLogTableName());
            database.setDatabaseChangeLogLockTableName("ACT_DE_" + database.getDatabaseChangeLogLockTableName());
            liquibase = new Liquibase("classpath:/liquibase/flowable-modeler-app-db-changelog.xml",
                    new ClassLoaderResourceAccessor(), database);
            liquibase.update("flowable");
            var5 = liquibase;
        } catch (Exception var9) {
            throw new FrameworkException("Error creating liquibase database", var9);
        } finally {
            this.closeDatabase(liquibase);
        }

        return var5;
    }

    private void closeDatabase(Liquibase liquibase) {
        if (liquibase != null) {
            Database database = liquibase.getDatabase();
            if (database != null) {
                try {
                    database.close();
                } catch (DatabaseException var4) {
                    log.warn("Error closing database", var4);
                }
            }
        }

    }
}
