# -*- coding: utf-8 -*-
from collections import namedtuple

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

ChangeValue = namedtuple('ChangeValue', ('table_number', 'source_schema', 'target_schema'))

VALUES_TO_CHANGE = [ChangeValue(874, 'Q3B', 'Q5B'),
                    ChangeValue(875, 'Q3B', 'Q5B')]


class MoveTablesToDifferentSchema(SQLPacket, ChangeDTPPacket):
    """Move several tables to a different schema

    First the autonumber rule of DT 477 is corrected from

        $$$$$$$$$
        to
        ;;;$$$$$$

    then 874 and 875 will be moved from Q3B to Q5B
    """
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 17913

    def get_dependencies(self):
        return (MinVersionDependency(version='39.5.6'),
                MaxVersionDependency(version='39.5.6'))

    def fix(self, packet_runner):
        errors = False

        system_license = ppms.uvar_get(SYS_VAR_LICENSE)
        if system_license == '011':
            self.log('No need to change the autonumber rule in a PLANTA system')
        else:
            record = self.get_record(dt_num=439, key_list=[system_license, '000443'], di_list=['number_constr_rule'])
            if not self.change_value(record=record, old_value='$$$$$$$$$', new_value=';;;$$$$$$',
                                     attribute='number_constr_rule'):
                return self.fail('Could not correct autonumber rule')

        for table_number, source_schema, target_schema in VALUES_TO_CHANGE:
            self.log_heading('Moving table {table_number} from {source_schema} to {target_schema}'.format(
                table_number=table_number, source_schema=source_schema, target_schema=target_schema))

            result = self.move_table_to_different_schema(table_number=table_number, source_schema=source_schema,
                                                         target_schema=target_schema)

            if not result:
                errors = True

        if errors:
            return self.fail('Not all tables could be moved')

        return self.success()
