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

from ppms import ppms
from ppms import ppms_cu
from ppms.constants import *
from ppms.migration import PacketCategory, MaxVersionDependency, VersionType, MinVersionDependency, \
    PacketDependency, PacketState, ChangeDTPPacket

NEW_CODE = r"""from ppms.constants import *
from ppms.project_rights import update_earned_value_analysis

def processInput(di, oldvalue):
    newvalue = di.get_value()
    
    if newvalue and newvalue != oldvalue:
        ppms.ui_message_id('1068')
        if ppms.msg_pop().get_reply() == MSG_REPLY_YES:
            update_earned_value_analysis()
            return newvalue
        return oldvalue
    return newvalue

processInput.deps = ("",)"""

SQL = {'000401': {DBMS_ORACLE: {'old': """BEGIN 

    DBMS_SCHEDULER.create_job (

      job_name     => 'PL_EVA_JOB_' || dbms_random.string('U', 15),

      job_type     => 'PLSQL_BLOCK',

      job_action   => 'BEGIN DBMS_SNAPSHOT.REFRESH (''V_EVA_VGR'', ''C''); DBMS_SNAPSHOT.REFRESH (''V_EVA_VG'', ''C''); DBMS_SNAPSHOT.REFRESH (''V_EVA_PR'', ''C''); END;',

      enabled      => TRUE,

      comments     => 'Updates the PLANTA EVA.');

END;""",
                                'new': """BEGIN "P_RUNNINGSUM_827"({do_complete}, '{pr_id}', '{report_id}'); END;"""},
                  DBMS_MSSQL: {'old': """UPDATE DT354 SET DI025544='a' where DI025544='a'""",
                               'new': """P_RUNNINGSUM_827 {do_complete}, '{pr_id}', '{report_id}'"""}}}


class FixEarnedValueCheckbox(ChangeDTPPacket):
    """Adds recalculation functionality to earned value checkbox in model parameters
    """
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 13876

    __PATH = r'migration.hotfix.S_39_5_14.WI10922_fix_earned_value.FixEarnedValueSchema'
    DBMS = ppms.db_get_dbms_name()

    def get_dependencies(self):
        return (MinVersionDependency(version='39.4', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.6', version_type=VersionType.CUSTOMIZING),
                PacketDependency(packet_path=self.__PATH, expected_state=PacketState.INSTALLED))

    def fix(self, runner):
        errors = ""

        record = self.get_record(412, ['061426'], ['wb_type', 'valuerange'])

        if not self.change_value(record=record, attribute='wb_type', old_value='', new_value='PY'):
            errors += 'Could not change valuerange type of DI061426 - maybe it was individualized?\n'

        if not self.change_value(record=record, attribute='valuerange', old_value='', new_value=NEW_CODE):
            errors += 'Could not change valuerange code of DI061426 - maybe it was individualized?\n'

        for id, dbms_mapping in SQL.items():
            rec = self.get_record(343, [self.DBMS, id], ['source_text_clob'])
            if not self.change_value(record=rec, attribute='source_text_clob', old_value=dbms_mapping[self.DBMS]['old'], new_value=dbms_mapping[self.DBMS]['new']):
                errors += 'Could not change SQL statement code of statement 000401 - maybe it was individualized?\n'

        # Workaround for WI 18755
        ppms.db_commit()

        if errors:
            return self.fail(errors)

        license_rec = ppms_cu.Helper.get_active_license_model()
        if license_rec:
            if license_rec.earned_value_active.get_value():
                ppms.db_modify(ppms.get_query('000401').format(do_complete=1, pr_id='', report_id=''))

        return self.success()