# -*- coding: utf-8 -*-
from ppms.migration import PacketCategory, MaxVersionDependency, VersionType, ChangeDTPPacket, SQLPacket

NEW_VALUERANGE = r"""from ppms import ppms_cu
from ppms import text_constant

def get_amount(query):
    query = ppms.get_query(query)
    results = ppms.db_select(query)

    try:
        return str(int(results[0][0]))
    except IndexError:
        return '0'

def computeOutput(di):
    projects = get_amount('000226')
    tasks = get_amount('000225')

    srqs = get_amount('000227')
    rsos = get_amount('000228')

    leads = get_amount('000229')
    planta_link = get_amount('000700')

    msp_link = get_amount('000701')

    text = text_constant.get_formatted_text_constant('001562', **locals())

    return text.replace(r'\n', '\n')

computeOutput.deps = ('*',)"""

OLD_VALUERANGE = r"""from ppms import ppms_cu

def get_amount(query):
    query = ppms.get_query(query)
    results = ppms.db_select(query)

    try:
        return str(int(results[0][0]))
    except IndexError:
        return '0'

def computeOutput(di):
    projects = get_amount('000226')
    tasks = get_amount('000225')

    srqs = get_amount('000227')
    rsos = get_amount('000228')

    leads = get_amount('000229')
    offers = get_amount('000230')

    assignments = get_amount('000231')

    contents = get_amount('000232')
    elements = get_amount('000233')

    text = ppms_cu.Access.get_text_constant(None, '001562')
    text = text.format(**locals())
    text = text.replace(r'\n', '\n')

    return text

computeOutput.deps = ('*',)"""


class ReplaceLizenzstaffelValuerange(ChangeDTPPacket):
    """Fix Python error when opening "Lizenzstaffel" module by correcting value range"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13769

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

    def fix(self, runner):
        record = self.get_record(dt_num=412, key_list=['059024'], di_list=['valuerange'])
        if not self.change_value(record=record, attribute='valuerange', old_value=OLD_VALUERANGE, new_value=NEW_VALUERANGE):
            return self.fail('Could not change DI 059024 - was it individualized?')

        return self.success()


class PortLizenzstaffelSQLStatements(SQLPacket):
    """Correct the SQL statements for fetching the amount of licensed records"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13769

    FILENAME = 'wi13769_fix_lizenzstaffel.sql'

    SQL_STATEMENTS = "('000226', '000225', '000227', '000228', '000229', '000700', '000701')"

    DELETE_QUERIES = ["DELETE DT342 WHERE DI024359 IN %s" % SQL_STATEMENTS,
                      "DELETE DT343 WHERE DI024373 IN %s" % SQL_STATEMENTS,
                      "DELETE DT435 WHERE DI023517 = '024371' AND DI001538 IN (SELECT DI024371 FROM DT342 WHERE DI024359 IN %s)" % SQL_STATEMENTS]

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

    def fix(self, runner):
        for delete_query in self.DELETE_QUERIES:
            self.modify_and_log(delete_query)

        self.apply_dml_file(self.sql_planta_de_dbms, self.FILENAME)

        return self.success()