# -*- coding: utf-8 -*-

from datetime import datetime

from application.model.configuration import Configurations
from mbcontextmessagehandler import MbContextMessageBus
from mwhelper import BaseRepository


class VersionsPOSRepository(BaseRepository):
    def __init__(self, message_bus, configs):
        # type: (MbContextMessageBus, Configurations) -> None

        super(VersionsPOSRepository, self).__init__(message_bus.mbcontext)

        self.configs = configs

    def get_last_versions(self):
        # type_id: () -> Dict[int, str]

        def inner_func(conn):
            # type_id: (Connection) -> Dict[int, str]

            query = """
                        SELECT TypeId, UpdateName, AppliedDate FROM
                        (
                            SELECT *
                            FROM UpdatesController
                            WHERE AppliedDate IS NOT NULL
                            ORDER BY AppliedDate DESC
                        )
                        GROUP BY TypeId
                    """

            cursor = conn.select(query)
            if not cursor.rows():
                return {}, {}

            versions = {}
            versions_dates = {}
            for version in cursor:
                type_id = int(version.get_entry("TypeId"))
                versions[type_id] = version.get_entry("UpdateName")
                applied_date = version.get_entry("AppliedDate")[:19]
                version_date = datetime.strptime(applied_date, "%Y-%m-%dT%H:%M:%S")
                versions_dates[type_id] = datetime.strftime(version_date, "%d/%m/%Y %H:%M")

            return versions, versions_dates

        return self.execute_with_connection(inner_func, service_name=self.configs.persistence_name)
