# -*- coding: utf-8 -*-
from ppms import ppms
from ppms.migration import *
import os


class PortNewDFBehaviourListboxValues(SQLPacket, ChangeDTPPacket):
    """Ports new module subclass behaviours for the DF behaviour column."""
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 21255

    new_valuerange = """from ppms.legitimate_df_behaviours import *

checkInput = check_behaviours_for_000221"""
    obsolete_python_module = "py/api/ppms/customizing/venus/ppms/legitimate_df_behaviours.py"

    filename = 'wi21255_port_new_df_behaviours.sql'
    deletion_file = 'wi21255_port_new_df_behaviours_delete.sql'

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

    def delete_old_data(self):
        self.log_heading('Wiping data that could cause conflicts')
        self.apply_dml_file(self.sql_planta_de_ansi, self.deletion_file)

    def insert_new_data(self):
        self.log_heading('Inserting new data')
        self.apply_dml_file(self.sql_planta_de_dbms, self.filename)

    def update_value_range(self):
        record = self.get_record(412, ['000221'], ['valuerange'])
        return self.change_value(record, 'valuerange', old_value=None, new_value=self.new_valuerange)

    # A py-file has been moved from customizing to server, which means it would exist twice after Server-Update -> Delete it from its old (obsolete) place
    def delete_obsolete_python_file(self):
        try:
            with ppms.messages_disabled():
                serverPath = ppms.uvar_get("@10")
                file_to_delete = os.path.join(serverPath, self.obsolete_python_module)
                os.remove(file_to_delete)
        except:
           # If this file didn't exist -> There was nothing to do anyway, soo, no problem 
           pass

    def fix(self, runner):
        with ppms.autocommit_disabled():
            self.delete_old_data()
            self.insert_new_data()

        if not self.update_value_range():
            return self.fail("Unable to update the valuerange for DI 000221. New values for the lisboxes are already inserted!")

        self.delete_obsolete_python_file()

        return self.success()
