from gi.repository import GObject

import logging

import iotas.config_manager
from iotas import const
from iotas.note import DirtyFields
from iotas.note_database import NoteDatabase


class MigrationAssistant(GObject.Object):
    def __init__(self, db: NoteDatabase):
        self.__db = db
        self.__version_migrations = {}
        self.__version_migrations["0.1.14"] = self.__make_keeping_webkit_in_memory_default

    def handle_version_migration(self) -> None:
        previous_version = iotas.config_manager.get_last_launched_version()
        current_version = const.VERSION
        if "-" in current_version:
            current_version = current_version.split("-")[0]
        if previous_version != current_version:
            if previous_version != "":
                if current_version > previous_version:
                    logging.info("Updating to v{}".format(current_version))
                    if current_version in self.__version_migrations:
                        self.__version_migrations[current_version]()
                else:
                    logging.info("Downgrading to v{}?".format(current_version))
                self.__regenerate_excerpts()
            iotas.config_manager.set_last_launched_version(current_version)

    def __regenerate_excerpts(self) -> None:
        notes = self.__db.get_all_notes(load_content=True)
        for note in notes:
            if note.regenerate_excerpt():
                changed_fields = DirtyFields()
                changed_fields.excerpt = True
                self.__db.persist_note_selective(note, changed_fields)

    def __make_keeping_webkit_in_memory_default(self):
        logging.info("Setting WebKit process to be retained in memory after first use")
        iotas.config_manager.set_markdown_keep_webkit_process(True)
