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

from ppms import ppms
from ppms.migration.packet import *

class CustomerDIDeactivation(SQLPacket):
    '''Deactivates customer-changed DIs that belong to Planta system tables (Q1B/Q2B)
       and writes the DIs that it finds into log file.

       These tables must not be changed, and the customer-inserted DIs belonging to them will be deactivated by this migration package.
       If you have inserted columns in these tables, you must correct your customizing
       (e.g. by outsourcing them to a specific table that does not belong to Q1B/Q2B, with a 1:1 relation to the table in Q1B/Q2B).

       After correcting your customizing, delete the columns in question to let this migration package succeed.
    '''
    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 11342

    # All DIs from Q1B & Q2B that were inserted by customer (identified by not having a standard license)
    select_query = """SELECT DI000238 FROM DT412 WHERE (DI000239 IN (SELECT DI000265 FROM DT415 WHERE DI000266 IN ('Q1B', 'Q2B'))
                                                        AND (DI001869 NOT IN ('000', '011', 'ZZZ'))
                                                        AND DI000275 = 0)"""
    change_dis = """UPDATE DT412 SET ENABLED = 0 WHERE DI000238 = '{0}'"""

    def fix(self, runner):
        dis = ppms.db_select(self.select_query)

        if (len(dis) > 0):
            # There should be no DIs in Q1B/Q2B that were modified by customer
            self.log('Found {0} columns from Q1B / Q2B in database that were changed by customer. They will be deactived. Please check your customizing!'.format(len(dis)))

            for di in dis:
                self.modify_and_log(self.change_dis.format(di[0]))

            return self.fail()
        else:
            self.log('No customer-changed DIs in system tables found, everything ok.')
            return self.success()
