# -*- coding: utf-8 -*-
from ppms.migration import SQLPacket, PacketCategory, \
    VersionType, MinVersionDependency, MaxVersionDependency

FILE = 'WI14220_dataitemport_db.sql'


class CreateDataitemsForAccountedReports(SQLPacket):
    """creates all necessary dataitems for monthly accounted reports"""

    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14220

    def get_dependencies(self):
        return(MinVersionDependency(version='39.5', version_type=VersionType.CUSTOMIZING),
               MaxVersionDependency(version='39.5.6', version_type=VersionType.CUSTOMIZING))

    def columns_already_exist(self):
        return self.column_exists(table_name='DT461', column_name='DI063607') and \
               self.column_exists(table_name='DT823', column_name='DI063608') and \
               self.column_exists(table_name='DT823', column_name='DI063609')

    def fix(self, packet_runner):
        if not self.columns_already_exist():
            # create data items
            self.apply_fix_ddl_file(self.sql_planta_de_dbms, FILE, split=True)

        # delete related S15 package, which is not needed
        package_path = "migration.hotfix.S_39_5_15.wi14220_monthly_accounted_reports.CreateDataitemsForAccountedReports"

        del_history = """delete from MIGRATIONHISTORY
                         where MIGRATIONRULE =
                            (select UUID
                             from MIGRATIONRULE
                             where PYTHONPATH = '{package_path}')
                             """.format(**locals())
        self.modify_and_log(del_history)

        del_mig_rule = """delete from MIGRATIONRULE
                          where PYTHONPATH = '{package_path}'
                          """.format(**locals())
        self.modify_and_log(del_mig_rule)

        return self.success()