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

df_config_change_list = [
('042805', '150257', '''from clock import Clock
from System.Drawing import Color
"""Create clock panel
para.1 - zoom_percentage int: zoom-percentage, default=100
para.2 - slice_color string: color of time slice, default=transparent - red ("#90FF3E00")
para.3 - slice_ticker int: set slice ticker, 0=second - ticker, 1=minute - ticker, default=0
"""
clock_panel = Clock(zoom_percentage=40)
#Get clock panel
ctl = clock_panel.winpanel
ctl.BackColor = Color.Transparent''',
'''try:
    from services.clock_controller import Clock
except ImportError:
    from clock import Clock
from System.Drawing import Color
"""Create clock panel
para.1 - zoom_percentage int: zoom-percentage, default=100
para.2 - slice_color string: color of time slice, default=transparent - red ("#90FF3E00")
para.3 - slice_ticker int: set slice ticker, 0=second - ticker, 1=minute - ticker, default=0
"""
clock_panel = Clock(zoom_percentage=40)
#Get clock panel
ctl = clock_panel.winpanel
ctl.BackColor = Color.Transparent'''),
('043582', '145450', '''import workflow_bar

# wi
import imp
imp.reload(workflow_bar)

#Create workflow object
workflow = workflow_bar.workflow(df)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent

del workflow''',
'''try:
    import workflow_bar_service as workflow_bar
except ImportError:
    import workflow_bar

#Create workflow object
workflow = workflow_bar.workflow(df)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent

del workflow'''),
('046036', '713953', '''import workflow_bar
# wi
import imp
imp.reload(workflow_bar)

da_id="46036"
df_id_all="713955"
df_id_current="713954"
#Create workflow object
workflow = workflow_bar.workflow(df,da_id,df_id_all,df_id_current)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent''',
'''try:
    import workflow_bar_service as workflow_bar
except ImportError:
    import workflow_bar

da_id="46036"
df_id_all="713955"
df_id_current="713954"
#Create workflow object
workflow = workflow_bar.workflow(df,da_id,df_id_all,df_id_current)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent'''),
('048369', '145450', '''import workflow_bar
# wi
import imp
imp.reload(workflow_bar)

#Create workflow object
workflow = workflow_bar.workflow(df)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent

del workflow''',
'''try:
    import workflow_bar_service as workflow_bar
except ImportError:
    import workflow_bar

#Create workflow object
workflow = workflow_bar.workflow(df)
#Get workflow panel
ctl = workflow.winpanel
ctl.BackColor = workflow_bar.Color.Transparent

del workflow''')
]

usermenu = {'old_value':
'''from ppms import ppms_cu
from ppms.show_alert import Start_Alert
import os, subprocess

def is_forking():
    def get_process_data(PID):
        PIPE = subprocess.PIPE
        File = subprocess.Popen('ps -e | grep {0}'.format(str(PID)), stdout=PIPE, shell=True, executable="/bin/bash").stdout
        return (str(File.readline()).replace("\\\\n'",''))

    try:
        father = get_process_data(os.getppid())
        child = get_process_data(os.getpid())

        father = father[father.rfind(' ') + 1:]
        child = child[child.rfind(' ') + 1:]

        if father == child:
            # Forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001248'))
        else:
            # No forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))
    except:
        # No forking
        return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))

#Function which gets executed on every server execute intervall
def news_polling_func():
    try:
        Start_Alert
    except:
        from ppms.show_alert import Start_Alert
    Start_Alert.start()

def start_polling():
    user_id = ppms.uvar_get('@1')

    #Set all user news to notified
    sql_update_notified = """update DT886 set DI041508=1 where DT886.DI041347='""" + user_id + """'"""
    ppms.db_modify(sql_update_notified)

    # register the new polling function
    ppms.start_service(news_polling_func, 500)

def poll_news():
    Start_Alert.start()

def on_load():
    start_polling()

    # Should we change the system title?
    CHANGE_TITLE = False
    APPEND_TITLE = False

    if CHANGE_TITLE:
        # Retrieve PID and PPID
        PID = os.getpid()
        PPID = ""
        try:
            PPID = os.getppid()
        except:
            pass

        # Retrieve some more useful data to display
        changeset = ppms.changeset_number()
        user = ppms.uvar_get("@1")

        record = ppms.search_record(346, [ppms.uvar_get('@G209')], [24729, 24725], False)
        db_user = record.user.get_value()
        connect_string = record.connect_string.get_value()

        if APPEND_TITLE:
            # Retrieve the title of the system
            new_title = ppms.search_record(345, [ppms.uvar_get('@3')], [25122], False).title.get_value()
        else:
            #new_title = ''
            # Temporary to mimick old behaviour
            if connect_string == 'pl39db' and db_user == 'D010':
                new_title = 'MASTER'
            else:
                new_title = 'Testsystem'

        new_title = "{0}: {1}, PID: {2} PPID: {3} - {4} - {5} - {6}@{7}".format(
                    new_title, changeset, PID, PPID, user, is_forking(), db_user,
                    connect_string)
        ppms.ui_set_system_title(new_title)

def on_initial_focus():
    pass

def on_focus():
    pass

def on_reset():
    mod = ppms.get_target_module()
    mod.menu(12)''',
'new_value': '''from ppms import ppms_cu
from ppms.show_alert import Start_Alert
import os, subprocess

from ppms.user_interface.clock_controller import ClockController
from ppms.user_interface.workflow_bar_handler import WorkflowBarHandler
from csrpc.utils import access
from csrpc.core import registration
from ppms.constants import *


def start_services():
    if ppms.protocol_version_in_boundaries(ProtocolVersion.RPC_MESSAGE, ProtocolVersion.UNDEFINED):
        clock_controller = registration.register_service('clock_controller', ClockController)
        workflow_bar_handler = registration.register_service('workflow_bar_handler', WorkflowBarHandler)

def is_forking():
    def get_process_data(PID):
        PIPE = subprocess.PIPE
        File = subprocess.Popen('ps -e | grep {0}'.format(str(PID)), stdout=PIPE, shell=True, executable="/bin/bash").stdout
        return (str(File.readline()).replace("\\\\n'",''))

    try:
        father = get_process_data(os.getppid())
        child = get_process_data(os.getpid())

        father = father[father.rfind(' ') + 1:]
        child = child[child.rfind(' ') + 1:]

        if father == child:
            # Forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001248'))
        else:
            # No forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))
    except:
        # No forking
        return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))

#Function which gets executed on every server execute intervall
def news_polling_func():
    try:
        Start_Alert
    except:
        from ppms.show_alert import Start_Alert
    Start_Alert.start()

def start_polling():
    user_id = ppms.uvar_get('@1')

    #Set all user news to notified
    sql_update_notified = """update DT886 set DI041508=1 where DT886.DI041347='""" + user_id + """'"""
    ppms.db_modify(sql_update_notified)

    # register the new polling function
    ppms.start_service(news_polling_func, 500)

def poll_news():
    Start_Alert.start()

def on_load():
    start_polling()
    start_services()

    # Should we change the system title?
    CHANGE_TITLE = True
    APPEND_TITLE = True

    if CHANGE_TITLE:
        # Retrieve PID and PPID
        PID = os.getpid()
        PPID = ""
        try:
            PPID = os.getppid()
        except:
            pass

        # Retrieve some more useful data to display
        changeset = ppms.changeset_number()
        user = ppms.uvar_get("@1")

        record = ppms.search_record(346, [ppms.uvar_get('@G209')], [24729, 24725], False)
        db_user = record.user.get_value()
        connect_string = record.connect_string.get_value()

        if APPEND_TITLE:
            # Retrieve the title of the system
            new_title = ppms.search_record(345, [ppms.uvar_get('@3')], [25112], False).title.get_value()
        else:
            #new_title = ''
            # Temporary to mimick old behaviour
            if connect_string == 'pl39db' and db_user == 'D010':
                new_title = 'MASTER'
            else:
                new_title = 'Testsystem'

        new_title = "{0}: {1}, PID: {2} PPID: {3} - {4} - {5} - {6}@{7}".format(
                    new_title, changeset, PID, PPID, user, is_forking(), db_user,
                    connect_string)
        ppms.ui_set_system_title(new_title)

def on_initial_focus():
    pass

def on_focus():
    pass

def on_reset():
    mod = ppms.get_target_module()
    mod.menu(12)'''}

alternative_usermenu = '''from ppms import ppms_cu
from ppms.show_alert import Start_Alert
import os, subprocess

def is_forking():
    def get_process_data(PID):
        PIPE = subprocess.PIPE
        File = subprocess.Popen('ps -e | grep {0}'.format(str(PID)), stdout=PIPE, shell=True, executable="/bin/bash").stdout
        return (str(File.readline()).replace("\\\\n'",''))

    try:
        father = get_process_data(os.getppid())
        child = get_process_data(os.getpid())

        father = father[father.rfind(' ') + 1:]
        child = child[child.rfind(' ') + 1:]

        if father == child:
            # Forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001248'))
        else:
            # No forking
            return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))
    except:
        # No forking
        return (ppms_cu.Access.get_text_constant(ppms.get_target_module(), '001249'))

#Function which gets executed on every server execute intervall
def news_polling_func():
    try:
        Start_Alert
    except:
        from ppms.show_alert import Start_Alert
    Start_Alert.start()

def start_polling():
    user_id = ppms.uvar_get('@1')

    #Set all user news to notified
    sql_update_notified = """update DT886 set DI041508=1 where DT886.DI041347='""" + user_id + """'"""
    ppms.db_modify(sql_update_notified)

    # register the new polling function
    ppms.start_service(news_polling_func, 500)

def poll_news():
    Start_Alert.start()

def on_load():
    start_polling()

    # Should we change the system title?
    CHANGE_TITLE = False
    APPEND_TITLE = False

    if CHANGE_TITLE:
        # Retrieve PID and PPID
        PID = os.getpid()
        PPID = ""
        try:
            PPID = os.getppid()
        except:
            pass

        # Retrieve some more useful data to display
        changeset = ppms.changeset_number()
        user = ppms.uvar_get("@1")

        record = ppms.search_record(346, [ppms.uvar_get('@G209')], [24729, 24725], False)
        db_user = record.user.get_value()
        connect_string = record.connect_string.get_value()

        if APPEND_TITLE:
            # Retrieve the title of the system
            new_title = ppms.search_record(345, [ppms.uvar_get('@3')], [25112], False).title.get_value()
        else:
            #new_title = ''
            # Temporary to mimick old behaviour
            if connect_string == 'pl39db' and db_user == 'D010':
                new_title = 'MASTER'
            else:
                new_title = 'Testsystem'

        new_title = "{0}: {1}, PID: {2} PPID: {3} - {4} - {5} - {6}@{7}".format(
                    new_title, changeset, PID, PPID, user, is_forking(), db_user,
                    connect_string)
        ppms.ui_set_system_title(new_title)

def on_initial_focus():
    pass

def on_focus():
    pass

def on_reset():
    mod = ppms.get_target_module()
    mod.menu(12)'''


class AddServices(ChangeDTPPacket):
    '''Replaces server_exec()/client_exec() with services'''
    run_on_startup = True
    done_after_success = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 15191

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

    def fix(self, runner):
        for da, df, oldvalue, newvalue in df_config_change_list:
            record = self.get_record(411, [da, int(df)], di_list=['iron_py_script'])

            if not self.change_value(record, attribute='iron_py_script', old_value=oldvalue, new_value=newvalue):
                return self.fail('Could not change the customizing, maybe there was a individual customizing')

        record = self.get_record(405, ['0099QC'], di_list=['py_macro_text'])

        if not self.change_value(record, attribute='py_macro_text', old_value=usermenu['old_value'],
                                 new_value=usermenu['new_value']) and not self.change_value(record,
                                                                                            attribute='py_macro_text',
                                                                                            old_value=alternative_usermenu,
                                                                                            new_value=usermenu[
                                                                                                'new_value']):
            return self.fail('Could not change the customizing, maybe there was a individual customizing')

        return self.success()
