import os

from application.model.configuration import SystemPaths
from application.util import LoggerUtil
from _CommonService import CommonService

logger = LoggerUtil.get_logger_name(__name__)


class StaticConfigurationService(object):
    @staticmethod
    def update_static_databases():
        # type: () -> None

        try:
            logger.info("Updating static databases")
            static_databases = os.path.join(SystemPaths.static_configuration_folder.value, "databases")
            if not os.path.exists(static_databases):
                logger.info("No static database to update")
                return

            CommonService.copy_all_content(static_databases, SystemPaths.genesis_databases_path.value)
            logger.info("Static databases updated")
        except Exception as _:
            logger.exception("Error updating static databases")

    @staticmethod
    def update_static_loaders():
        # type: () -> None

        try:
            logger.info("Updating static loaders")
            static_loaders = os.path.join(SystemPaths.static_configuration_folder.value, "loaders")
            if not os.path.exists(static_loaders):
                logger.info("No static loader to update")
                return

            for directory in os.listdir(static_loaders):
                static_directory_path = os.path.join(static_loaders, directory)
                directory_path = os.path.join(SystemPaths.genesis_data_path.value, directory)
                CommonService.create_dir(directory_path, False)
                CommonService.copy_all_content(static_directory_path, directory_path)
        except Exception as _:
            logger.exception("Error updating static loaders")

    @staticmethod
    def run_databases_script():
        # type: () -> None

        try:
            logger.info("Running static scripts")
            static_scripts = os.path.join(SystemPaths.static_configuration_folder.value, "scripts")
            if not os.path.exists(static_scripts):
                logger.info("No static scripts to update")
                return

            for script in os.listdir(static_scripts):
                if not script.endswith(".sql"):
                    continue

                database_name = script.replace(".sql", ".db")
                logger.info("Running script for {}".format(database_name))
                script_path = os.path.join(static_scripts, script)
                database = os.path.join(SystemPaths.genesis_databases_path.value, database_name)
                if not os.path.exists(database):
                    logger.info("No database found {}".format(database))
                    continue

                backup_database = database.replace(".db", "_bkp.db")
                try:
                    CommonService.duplicate_file(database, backup_database)
                    CommonService.execute_scripts_commands(database, script_path, logger)
                    logger.info("Script executed for {}".format(database))
                except Exception as _:
                    logger.exception("Error running script for {}".format(script))
                    CommonService.remove_file(database)
                    CommonService.duplicate_file(backup_database, database)
                finally:
                    CommonService.remove_file(backup_database)
        except Exception as _:
            logger.exception("Error running static scripts")
