# -*- coding: latin-1 -*-
from ppms.migration import SQLPacket, PacketCategory
from ppms import ppms


class SetOwnerLicenseForZZZRecords(SQLPacket):
    '''Sets all owner license fields which have a owner license of 'ZZZ' to '011'.

    Sets all owner license fields which have a owner license of 'ZZZ' to '011' for Q1B, Q2B and most of Q3B.
    '''
    wi_number = 17774
    done_after_success = False
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY

    exclude_tables = ['511', '516', '518', '527', '525', '818', '887', '443', '324', '504', '526']
    include_schemas = ['Q1B', 'Q2B', 'Q3B']

    def fix(self, runner):
        ddict = ppms.get_data_dictionary()
        update_info = {}
        for dt_id, dt_obj in ddict.data_tables.items():
            if dt_obj.schema.id not in self.include_schemas:
                # skip schema which are not in include_schemas list
                continue

            dt_id = str(dt_id).zfill(3)
            if dt_id in self.exclude_tables:
                # exclude tables from exclude list (user related tables)
                continue

            dt_sql_name = dt_obj.sql_name
            if dt_sql_name[:2] == 'V_':
                # exclude views
                continue

            acr_dis = dt_obj.acr_dis
            if not acr_dis:
                # exclude tables without object protection
                continue

            # set license DI to 011 for all records with license 'ZZZ'
            lic_id_name = acr_dis[5].sql_name
            sql = """update {dt_sql_name}
                     set {lic_id_name} = '011' where {lic_id_name} = 'ZZZ'""".format(**locals())

            modified = ppms.db_modify(sql)

            self.log('Update result of table ' + str(dt_id) + ': ' + str(modified) + ' rows have been updated.')
        return self.success()