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


OLD_CODE = """from ppms import ppms_cu

def check_distributor_type(member_id,pr_id):
    returnvalue=[False,0]

    sql=ppms.get_query("000266").format(member_id,pr_id)
    distributor_type=ppms.db_select(sql)
    if len(distributor_type) > 0:
        if distributor_type[0][0] in (52,53):
            returnvalue=[True,distributor_type[0][0]]

    return returnvalue

def send_news_as_email(message_rec):
    recipients_email=mod_obj.recipient_email_list
    if len(recipients_email) > 0:
        my_email=ppms_cu.Helper.get_email_adress(ppms.uvar_get("@1"))
        subject=message_rec.title.get_raw_value()
        email_body=message_rec.description.get_raw_value()

        ppms_cu.Action.send_email(my_email,recipients_email,subject,email_body)

def check_message_and_save():
    message_recs=mod_obj.message.get_records()
    for message_rec in message_recs:
        if message_rec.title.get_raw_value() == "":
            ppms.ui_message_id("0047")
        else:
            mod_obj.menu(34)
            send_news_as_email(message_rec)
            mod_obj.menu(49)

def insert_message(pr_id,title,message,news_type,recipients):
    #prepare default values
    if title == "":
        title=ppms_cu.Helper.get_const_title("001129")
    if message == "":
        message=" "

    if type(recipients) != list:
        recipient_list=[recipients]
    else:
        recipient_list=recipients

    ppms.echo_off()

    #create news head
    target_rec=mod_obj.get_root(0).insert_record_into_da("message")
    target_rec.pr_id.set_raw_value(pr_id)
    target_rec.title.set_raw_value(title)
    target_rec.description.set_raw_value(message)

    target_rec.news_type.set_raw_value(news_type)
    target_rec.time_string.set_raw_value(target_rec.current_time.get_text_value())

    #mod_obj.menu(34)

    recipient_email_list=[]
    for recipient in recipient_list:
        recipient_rec=target_rec.insert_child("recipient")
        recipient_rec.recipient_id.set_raw_value(recipient)

        # check mail distribution
        check_distributor=mod_obj.check_distributor_type(recipient,pr_id)
        recipient_rec.deliviered_as_news_type.set_raw_value(int(check_distributor[1]))

        if check_distributor[0] == True:
            recipient_email_list.append(ppms_cu.Helper.get_email_adress(recipient))
        if check_distributor[1] == 52.0:
            recipient_rec.read.set_raw_value(1)
            recipient_rec.notified.set_raw_value(1)

    setattr(mod_obj, 'recipient_email_list', recipient_email_list)

    ppms.echo_on()

mod_obj=ppms.get_target_module()

def on_load():
    mod_obj.insert_message=insert_message
    mod_obj.check_distributor_type=check_distributor_type
    mod_obj.check_message_and_save=check_message_and_save
    mod_obj.send_news_as_email=send_news_as_email
def on_initial_focus():
    pass
def on_focus():
    pass
def on_reset():
    mod_obj.menu(49)"""
SUBCLASS_PATH = 'ppms.module_subclasses.send_info.SendInfoModule'


class ReplaceSendInfoMacro(ChangeDTPPacket):
    """Replace the old send info macro with the new subclass"""
    done_after_success = True
    run_on_startup = True
    category = PacketCategory.CATEGORY_MANDATORY
    wi_number = 14272

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

    def fix(self, runner):
        record = self.get_record(dt_num=405, key_list=['009A1T'], di_list=['py_macro_text', 'python_module_subclass'])
        if not self.change_value(record=record, attribute='py_macro_text', old_value=OLD_CODE, new_value=''):
            return self.fail('Could not change macro 009BC9 - was it individualized?')

        if not self.change_value(record=record, attribute='python_module_subclass', old_value='',
                                 new_value=SUBCLASS_PATH) and \
                not self.change_value(record, 'python_module_subclass', 'ppms.module_subclasses.base_class.Base',
                                      SUBCLASS_PATH):
            return self.fail('Could not change module subclass for module 009BC9 - was it individualized?')

        return self.success()