# -*- coding: utf-8 -*-
import os

from ppms.migration.packet import *


class CreateCustomizerFlagPacket(SQLPacket):
    '''Add flag for determining which users receive customizing error messages.

    Adds a customizer flag column to DT511 with default value of '0' and then
    sets it to '1' depending on the user's access to MOD000855 "Module".
    '''
    version = 1
    wi_number = 10139
    done_after_success = True
    run_on_startup = False
    category = PacketCategory.CATEGORY_OPTIONAL

    fname = 'wi10139_customizer_flag.sql'

    add_to_table = {'000002': """ALTER TABLE DT511 ADD (DI060055 NUMBER (5) DEFAULT 0 NOT NULL)""",
                    '000004': """ALTER TABLE DT511 ADD DI060055 [numeric](5, 0) NOT NULL DEFAULT 0"""}
    set_default = """UPDATE DT511 SET DI060055 = 1
WHERE
  DI010323 IN (SELECT DI010697 FROM DT518
               WHERE
                 DI010699 IN (SELECT DI010333 FROM DT512
                              WHERE
                                DI010332 IN (SELECT DI010325 FROM DT515
                                             WHERE
                                               DI010327 = '000855')))"""

    def fix(self, runner):
        sqlpath = self.get_sql_file_path(self.sql_planta_de_dbms, self.fname)
        queries = self.get_queries_from_file(sqlpath)

        self.add_customizer_flag_to_dt511()

        for query in queries:
            self.modify_and_log(query)

        self.log('Setting value...')
        self.modify_and_log(self.set_default)

        return self.success()

    def add_customizer_flag_to_dt511(self):
        self.log('Adding column...')
        query = self.add_to_table[self.DBMS]

        self.modify_and_log(query)