#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
    unmanic.database.py

    Written by:               Josh.5 <jsunnex@gmail.com>
    Date:                     14 Aug 2021, (12:03 PM)

    Copyright:
           Copyright (C) Josh Sunnex - All Rights Reserved

           Permission is hereby granted, free of charge, to any person obtaining a copy
           of this software and associated documentation files (the "Software"), to deal
           in the Software without restriction, including without limitation the rights
           to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
           copies of the Software, and to permit persons to whom the Software is
           furnished to do so, subject to the following conditions:

           The above copyright notice and this permission notice shall be included in all
           copies or substantial portions of the Software.

           THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
           EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
           MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
           IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
           DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
           OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
           OR OTHER DEALINGS IN THE SOFTWARE.

"""
import importlib
import inspect
import os

from peewee import SqliteDatabase, Field
from peewee_migrate import Router

from unmanic.libs import unlogger
from unmanic.libs.unmodels import list_all_models
from unmanic.libs.unmodels.lib import BaseModel


class Migrations(object):
    """
    Migrations

    Handle all migrations during application start.
    """

    logger = None
    database = None

    def __init__(self, config):
        unmanic_logging = unlogger.UnmanicLogger.__call__()
        self.logger = unmanic_logging.get_logger(__class__.__name__)

        # Based on configuration, select database to connect to.
        if config['TYPE'] == 'SQLITE':
            # Create SQLite directory if not exists
            db_file_directory = os.path.dirname(config['FILE'])
            if not os.path.exists(db_file_directory):
                os.makedirs(db_file_directory)
            self.database = SqliteDatabase(config['FILE'])

            self.router = Router(database=self.database,
                                 migrate_table='migratehistory_{}'.format(config.get('MIGRATIONS_HISTORY_VERSION')),
                                 migrate_dir=config.get('MIGRATIONS_DIR'),
                                 logger=self.logger)

    def __log(self, message, level='info'):
        if self.logger:
            getattr(self.logger, level)(message)
        else:
            print(message)

    def __run_all_migrations(self):
        """
        Run all new migrations.
        Migrations that have already been run will be ignored.

        :return:
        """
        self.router.run()

    def update_schema(self):
        """
        Updates the Unmanic database schema.

        Newly added tables/models and columns/fields will be automatically generated by this function.
        This way we do not need to create a migration script unless we:
            - rename a column/field
            - delete a column/field
            - delete a table/model

        :return:
        """
        # Fetch all model classes
        all_models = []
        for model in list_all_models():
            imported_model = getattr(importlib.import_module("unmanic.libs.unmodels"), model)
            if inspect.isclass(imported_model) and issubclass(imported_model, BaseModel):
                all_models.append(imported_model)

        # Start by creating all models
        self.__log("Initialising database tables")
        try:
            with self.database.transaction():
                for model in all_models:
                    self.router.migrator.create_table(model)
                self.router.migrator.run()
        except Exception:
            self.database.rollback()
            self.__log("Initialising tables failed", level='exception')
            raise

        # Migrations will only be used for removing obsolete columns
        self.__run_all_migrations()

        # Newly added fields can be auto added with this function... no need for a migration script
        # Ensure all files are also present for each of the model classes
        self.__log("Updating database fields")
        for model in all_models:
            # Fetch all peewee fields for the model class
            # https://stackoverflow.com/questions/22573558/peewee-determining-meta-data-about-model-at-run-time
            fields = model._meta.fields
            # loop over the fields and ensure each on exists in the table
            field_keys = [f for f in fields]
            for fk in field_keys:
                field = fields.get(fk)
                if isinstance(field, Field):
                    if not any(f for f in self.database.get_columns(model._meta.name) if f.name == field.name):
                        # Field does not exist in DB table
                        self.__log("Adding missing column")
                        try:
                            with self.database.transaction():
                                self.router.migrator.add_columns(model, **{field.name: field})
                                self.router.migrator.run()
                        except Exception:
                            self.database.rollback()
                            self.__log("Update failed", level='exception')
                            raise
