# -*- coding: utf-8 -*-
from ppms.migration import SQLPacket, PacketCategory, MaxVersionDependency, VersionType
import planta
from collections import namedtuple
from ppms.constants import DBMS_ORACLE, DBMS_MSSQL

Replacement = namedtuple('Replacement', ['old_module', 'new_module'])

MODULES_TO_REPLACE = [Replacement('0099FF', '009CSD')]  # multi portfolio board


class MigratePortfolioWorkAreas(SQLPacket):
    """Migrates customer work areas to use the new portfolio modules instead of the outdated old ones."""
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_HELPER
    wi_number = 19954

    def fix(self, packet_runner):
        return self.migrate_customer_work_areas()

    def migrate_customer_work_areas(self):
        owner_license = planta.uvar_get('@3').zfill(3)
        select_work_areas = """select DI010325 from DT515
                                                 WHERE DI010327 = '{old_mod_id}'
                                                 and DI010395 = '{owner_license}'"""
        update_statement = """update DT515 set DI010327 = '{new_mod_id}'
                                                 WHERE DI010327 = '{old_mod_id}'
                                                 and DI010395 = '{owner_license}'"""

        for replacement in MODULES_TO_REPLACE:
            formated_select = select_work_areas.format(old_mod_id=replacement.old_module, owner_license=owner_license)
            work_area_list = [area[0] for area in planta.db_select(formated_select)]
            formated_query = update_statement.format(old_mod_id=replacement.old_module,
                                                     new_mod_id=replacement.new_module,
                                                     owner_license=owner_license)
            amount_of_work_areas = planta.db_modify(formated_query)

            work_areas = ", ".join(work_area_list)
            log_message = """Updated {amount_of_work_areas} work area(s) - changed module {old_mod_id} to {new_mod_id} in the following work area(s): {work_areas}"""
            self.log(log_message.format(amount_of_work_areas=amount_of_work_areas, old_mod_id=replacement.old_module,
                                        new_mod_id=replacement.new_module, work_areas=work_areas))

        return self.success()
