# -*- coding: utf-8 -*-
import os

from ppms import ppms
from ppms.migration import ChangeDTPPacket, SQLPacket, PacketCategory, MaxVersionDependency, VersionType


class AddTrafficLightForDeactivatedDIs(SQLPacket):
    '''Create traffic lights for inactive DIs.

    Four new Dataitems will be created.
    They show the "Enabled" value of the original Dataitem
    or change the highlighting on DIs/DDIs, respectively.
    '''

    wi_number = 9998
    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY

    sql_file = 'WI9998_add_traffic_light_for_deactivated_dis.sql'

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

    def fix(self, runner):
        check_query = "select 1 from dt412 where di000238 in ('063171', '063172')"
        cu_queries = ["update dt411 set di000203 = '062620' where di000306 = '001738' and di000307 = 2194",
                      "update dt411 set di000203 = '062620' where di000306 = '001738' and di000307 = 3937",
                      "update dt411 set di000203 = '063171' where di000306 = '001739' and di000307 = 501",
                      "update dt411 set di000203 = '063171' where di000306 = '001739' and di000307 = 1845"]
        
        sqlpath = self.get_sql_file_path(self.sql_planta_de_dbms, self.sql_file)
        queries = self.get_queries_from_file(sqlpath)
        queries += cu_queries
        
        errors = 0

        if ppms.db_select(check_query):
            self.log('One or more Dataitems already exist')
            for query in queries:
                try:
                    if not self.modify_and_log(query):
                        errors += 1
                except ppms.DatabaseError:
                    self.log("Error: Query '%s' failed!" % query)
                    errors += 1
        else:
            for query in queries:
                if not self.modify_and_log(query):
                    errors += 1
        
        if not errors:
            return self.success()
        return self.fail()

class AddMessagesForDeactivatedDIs(ChangeDTPPacket):
    '''Add dialog messages to the related value ranges'''

    wi_number = 9998
    version = 1
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY

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

    def fix(self, runner):
        valueranges = {'000213':["""def processInput(di, oldvalue):
    dtp_rec = di.get_dtp_record()
    newVal=di.get_value()
    if newVal != "":
        di_id = dtp_rec.di.get_value()
        #get di record
        di_dtp_rec=ppms.search_record(412, [di_id], [253,3141,244,1700,60111,1591], True)

        if di_dtp_rec != None:
            ppms_type=di_dtp_rec.ppms_type.get_value()
            ppms_class=di_dtp_rec.di_class.get_value()
            ppms_df_type=di_dtp_rec.df_type.get_value()
            ppms_enabled = di_dtp_rec.enabled.get_value()
            ppms_name = di_dtp_rec.di_name.get_value()

            if not ppms_enabled:
                ppms.ui_message_id('0977') 

            if (ppms_class == 1):
                dtp_rec.__getattr__("behavior").set_string_value("ba")

            if (str(di_id) == '004336'):
                dtp_rec.__getattr__("behavior").set_string_value("c4")

            if (str(di_id) == '025581'):
                dtp_rec.__getattr__("behavior").set_string_value("a")

            if (str(ppms_df_type) == 'AM'):
                dtp_rec.__getattr__("behavior").set_string_value("h")

            if (str(ppms_df_type) == 'Y' and str(di_id) != '004336' and str(di_id) != '025581'):
                dtp_rec.__getattr__("behavior").set_string_value("i2")
            if oldvalue =="":
                if (str(ppms_df_type) != 'AM' and str(di_id) != '025581' and str(di_id) != '004336' and ppms_class != 1 and str(ppms_df_type) != 'Y'):
                    dtp_rec.__getattr__("behavior").set_string_value("i")
    
    return di.get_value()
processInput.deps=('DI000221',)""", """def processInput(di, oldvalue):
    dtp_rec = di.get_dtp_record()
    newVal=di.get_value()
    if newVal != "":
        di_id = dtp_rec.di.get_value()
        #get di record
        di_dtp_rec=ppms.search_record(412, [di_id], [253,3141,244,1700], True)


        if di_dtp_rec != None:
            ppms_type=di_dtp_rec.ppms_type.get_value()
            ppms_class=di_dtp_rec.di_class.get_value()
            ppms_df_type=di_dtp_rec.df_type.get_value()

            if (ppms_class == 1):
                dtp_rec.__getattr__("behavior").set_string_value("ba")

            if (str(di_id) == '004336'):
                dtp_rec.__getattr__("behavior").set_string_value("c4")

            if (str(di_id) == '025581'):
                dtp_rec.__getattr__("behavior").set_string_value("a")

            if (str(ppms_df_type) == 'AM'):
                dtp_rec.__getattr__("behavior").set_string_value("h")

            if (str(ppms_df_type) == 'Y' and str(di_id) != '004336' and str(di_id) != '025581'):
                dtp_rec.__getattr__("behavior").set_string_value("i2")
            if oldvalue =="":
                if (str(ppms_df_type) != 'AM' and str(di_id) != '025581' and str(di_id) != '004336' and ppms_class != 1 and str(ppms_df_type) != 'Y'):
                    dtp_rec.__getattr__("behavior").set_string_value("i")
    
    return di.get_value()
processInput.deps=('DI000221',)"""],
                       '000391':["""from ppms import ppms

def processInput(di, oldvalue):
    dtp_rec = di.get_dtp_record()
    diVal = di.get_value()
    if diVal != "":
        di_id = dtp_rec.ddi.get_value()
        di_dtp_rec=ppms.search_record(412, [di_id], [60111], True)
        if di_dtp_rec != None:
            ppms_enabled = di_dtp_rec.enabled.get_value()
            if not ppms_enabled:
                ppms.ui_message_id('0977') 
    return str(diVal)
 
processInput.deps = ('',)

'''
def processInput(di, oldvalue):
    dtpRec = di.get_dtp_record()
    diVal = di.get_value()
    name = dtpRec.name.get_value()
    dt_id = dtpRec.dt_title.get_value()
    if name == "":
        dtpRec.name.set_string_value(str(dt_id))
    else:
        dtpRec.name.set_string_value(str(name))
    return str(diVal)
 
processInput.deps = ('DI001589','DI003389')
'''""", """from ppms import ppms

def processInput(di, oldvalue):
    dtpRec = di.get_dtp_record()
    diVal = di.get_value()
    name = dtpRec.name.get_value()
    dt_id = dtpRec.dt_title.get_value()
    if name == "":
        dtpRec.name.set_string_value(str(dt_id))
    else:
        dtpRec.name.set_string_value(str(name))
    return str(diVal)
 
processInput.deps = ('DI001589','DI003389')"""]}

        errors = 0

        for di, values in valueranges.items():
            rec = self.get_record(412, [di], ['valuerange'])
            new_value = values[0]
            old_value = values[1]
            if rec:
                if not self.change_value(rec, 'valuerange', old_value, new_value):
                    errors += 1
            else:
                errors += 1

        if not errors:
            return self.success()
        return self.fail()