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


class PortfolioMigPackageForMonthlyReportDateField(SQLPacket, ChangeDTPPacket):
    '''Updates portfolios and portfolio-reports with a monthly date
    
    Updates the dataitems DI062992 and DI062993 with a date (first of a month), 
    based on the date of creation for portfolio or the status of portfolio reports,
    when these dataitems are empty.'''
    
    wi_number = 12364
    version = 1
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    
    sql_file = 'wi12364_PortfolioMigPackageForMonthlyReportDateField.sql'

    DATAITEMS={'062992':'870',
               '062993':'090'}
               
    def get_dependencies(self):
        return (MinVersionDependency(version='39.5', version_type=VersionType.CUSTOMIZING),
                MaxVersionDependency(version='39.5.5', version_type=VersionType.CUSTOMIZING))  

    def dataitem_exist(self, dataitem):
        dt412_rec = self.get_record(412, [dataitem], [239])
        if dt412_rec:
            return dt412_rec.dt.get_value() == self.DATAITEMS[dataitem]

        return False

    def fix(self, runner):
        for dataitem in self.DATAITEMS.keys():
            if not self.dataitem_exist(dataitem): 
                err_message = "Update failed! The dataitem DI{0} does not exist!".format(dataitem)
                return self.skip(err_message)

        self.apply_dml_file(self.sql_planta_de_dbms, self.sql_file)

        return self.success()