package fi.nls.oskari.servlet;

import fi.nls.oskari.cache.JedisManager;
import fi.nls.oskari.db.DatasourceHelper;
import org.oskari.helpers.FlywaydbMigrator;
import fi.nls.oskari.log.LogFactory;
import fi.nls.oskari.log.Logger;
import fi.nls.oskari.scheduler.SchedulerService;
import fi.nls.oskari.util.ConversionHelper;
import fi.nls.oskari.util.PropertyUtil;
import org.quartz.SchedulerException;

import javax.naming.Context;


/**
 * Created by SMAKINEN on 8.7.2015.
 */
public class WebappHelper {

    private static final DatasourceHelper DS_HELPER = DatasourceHelper.getInstance();
    private static final String KEY_REDIS_HOSTNAME = "redis.hostname";
    private static final String KEY_REDIS_PORT = "redis.port";
    private static final String KEY_REDIS_POOL_SIZE = "redis.pool.size";

    private static final String STR_LOG_LINE = "#########################################################";


    private static Logger log = LogFactory.getLogger(WebappHelper.class);
    private static SchedulerService schedulerService;
    private static boolean propsLoaded = false;

    private WebappHelper() {}

    public static void loadProperties() {
        // populate properties
        System.out.println("- loading /oskari.properties");
        PropertyUtil.loadProperties("/oskari.properties");
        System.out.println("- loading /oskari-ext.properties");
        PropertyUtil.loadProperties("/oskari-ext.properties");
        // init logger after the properties so we get the correct logger impl
        log = LogFactory.getLogger(WebappHelper.class);
        propsLoaded = true;
    }

    public static void init() {
        try {
            if(!propsLoaded) {
                loadProperties();
            }
            // catch all so we don't get mysterious listener start errors
            log.info(STR_LOG_LINE);
            log.info("Oskari-map context is being initialized");
            initializeOskariContext();

            // init jedis
            log.info("Initializing Redis connections");
            JedisManager.connect(
                    ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_POOL_SIZE), 30),
                    PropertyUtil.get(KEY_REDIS_HOSTNAME, "localhost"),
                    ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_PORT), 6379));
            log.info("Oskari-map context initialization done");
            log.info(STR_LOG_LINE);
        } catch (Exception ex) {
            log.error(ex, "!!! Error initializing context for Oskari !!!");
        }

        migrateDB();

        schedulerService = new SchedulerService();
        try {
            schedulerService.initializeScheduler();
        } catch (final SchedulerException e) {
            log.error(e, "Failed to start up the Oskari scheduler");
        }
    }

    /**
     * Main initialization method
     */
    public static void initializeOskariContext() {

        log.info("- checking default DataSource");
        final Context ctx = DS_HELPER.getContext();
        if(!DS_HELPER.checkDataSource(ctx)) {
            log.error("Couldn't initialize default DataSource");
        }

        // loop "db.additional.pools" to see if we need any more pools configured
        log.info("- checking additional DataSources");
        final String[] additionalPools = DS_HELPER.getAdditionalModules();
        for(String pool : additionalPools) {
            if(!DS_HELPER.checkDataSource(ctx, pool)) {
                log.error("Couldn't initialize DataSource for module:", pool);
            }
        }
    }

    private static void migrateDB() {
        if(PropertyUtil.getOptional("db.flyway", true) == false) {
            log.warn("Skipping flyway migration! Remove 'db.flyway' property or set it to 'true' to enable migration");
            return;
        }
        boolean ignoreMigrationFailures = PropertyUtil.getOptional("db.ignoreMigrationFailures", false);

        // upgrade database structure with http://flywaydb.org/
        log.info("Oskari-map checking DB status");
        try {
            FlywaydbMigrator.migrate(DS_HELPER.getDataSource());
            log.info("Oskari core DB migrated successfully");
        } catch (Exception e) {
            log.error(e, "DB migration for Oskari core failed!");
            if(!ignoreMigrationFailures) {
                throw e;
            }
        }
        final String[] additionalPools = DS_HELPER.getAdditionalModules();
        for(String module : additionalPools) {
            final String poolName = DS_HELPER.getOskariDataSourceName(module);
            try {
                FlywaydbMigrator.migrate(DS_HELPER.getDataSource(poolName), module);
                log.info(module + " DB migrated successfully");
            } catch (Exception e) {
                log.error(e, "DB migration for module", module, "failed!");
                if(!ignoreMigrationFailures) {
                    throw e;
                }
            }
        }
    }

    public static void teardown() {
        if (schedulerService != null) {
            try {
                schedulerService.shutdownScheduler();
            } catch (final SchedulerException e) {
                log.error(e, "Failed to shut down the Oskari scheduler");
            }
        }
        DS_HELPER.teardown();
        JedisManager.shutdown();
        log.info("Context destroy");
    }
}

@@ -275,52 +275,8 @@
 ce;%0A
-import fi.nls.oskari.util.ConversionHelper;%0A
 impo
@@ -311,16 +311,16 @@
 tyUtil;%0A
+
 import o
@@ -543,215 +543,8 @@
 e();
-%0A    private static final String KEY_REDIS_HOSTNAME = %22redis.hostname%22;%0A    private static final String KEY_REDIS_PORT = %22redis.port%22;%0A    private static final String KEY_REDIS_POOL_SIZE = %22redis.pool.size%22;
 %0A%0A  
@@ -1806,251 +1806,8 @@
 ect(
-%0A                    ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_POOL_SIZE), 30),%0A                    PropertyUtil.get(KEY_REDIS_HOSTNAME, %22localhost%22),%0A                    ConversionHelper.getInt(PropertyUtil.get(KEY_REDIS_PORT), 6379)
 );%0A 
@@ -2799,32 +2799,39 @@
 nalPools = D
-S_HELPER
+atasourceHelper
 .getAddition
@@ -3899,32 +3899,39 @@
 nalPools = D
-S_HELPER
+atasourceHelper
 .getAddition

Remove redis props from helper and use defaults