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


class SetDatabaseVersion(ChangeDTPPacket):
    """Set the data_base_changeset datafield to the (estimated) correct value

    This packet checks if the budget table 281 exists in the system.
    If it doesn't it sets the data_base_changeset field to 39.4, 39.5 if it does exist
    """
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 12687

    def get_dependencies(self):
        return (MaxVersionDependency('39.5.6'), )

    def fix(self, runner):
        table_record = ppms.search_record(415, ['281'], ['dt_id'])

        if table_record is None:
            data_base_changeset = '39.4'

            system_parameter_record = self.get_record(dt_num=345, key_list=[ppms.uvar_get(SYS_VAR_LICENSE)],
                                                      di_list=['data_base_changeset'])
            old_value = system_parameter_record.data_base_changeset.get_value()

            if self.change_value(record=system_parameter_record, attribute='data_base_changeset',
                                 old_value=old_value, new_value=data_base_changeset):
                return self.success()
            else:
                return self.fail('Could not set data base changeset')

        return self.success()