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

import itertools

from ppms import ppms
from ppms.constants import *
from ppms.migration import SQLPacket, PacketCategory, MinVersionDependency, MaxVersionDependency, VersionType

class FixWrongColumnType(SQLPacket):
    """Change column type of DI041079, DI002747 and DI002748 from itext to varchar.

    Also replaces the values of DI002747 and DI002748 with the translation of their current language (@19 of user MIGRATION)."""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 17638

    ALTER_TABLE = {DBMS_ORACLE: "alter table DT483 modify %s varchar2(80)",
                   DBMS_MSSQL: "alter table DT483 alter column %s varchar(80)"}

    DROP_CONSTRAINTS = ["""alter table DT483 drop constraint DT483_002747""", """alter table DT483 drop constraint DT483_002748"""]



    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.5', version_type=VersionType.CUSTOMIZING))

    def fix(self, runner):
        for drop in self.DROP_CONSTRAINTS:
            try:
                self.modify_and_log(drop)
            except ppms.DatabaseError:
                pass
        for di in ("DI002747", "DI002748"):
            i_nos = list(itertools.chain.from_iterable(ppms.db_select("select %s from DT483" % di)))
            self.modify_and_log(self.ALTER_TABLE[self.DBMS] % di)
            self.modify_and_log("update DT412 set DI041246 = 5, DI000253 = 'X', DI000244 = 'AL', DI003141 = 'AL', DI001700 = 0 where DI000239 = '483' and DI000215 = '%s' and DI041246 = 17" % di)
            self.modify_and_log("update DT483 set %s = (select DI010275 from DT545 where DI010261 = %s and DI010262 = '%s')" % (di, di, ppms.uvar_get(SYS_VAR_LANGUAGE)))
            for i_no in i_nos:
                self.modify_and_log("delete from DT545 where DI010261 = %i" % i_no)

        self.modify_and_log("update DT412 set DI041246 = 5, DI000253 = 'X', DI000244 = 'AL', DI003141 = 'AL', DI001700 = 0, DI000246 = 30 where DI000239 = '472' and DI000238 = '041079' and DI041246 = 17 and DI000246 = 20")

        return self.success()