'Parse Responses
- reply to mails from the Monitor service
- parse mails directed to the Deploy Module
@ToDo: Use template for format of field/value encoding'

@staticmethod
def parse_email(message):

    db = current.db
    s3db = current.s3db
    reply = None
    message_id = message.message_id
    table = s3db.msg_email
    record = db((table.message_id == message_id)).select(table.raw, limitby=(0, 1)).first()
    if (not record):
        return reply
    message_body = record.raw
    if (not message_body):
        return reply
    if (':run_id:' in message_body):
        try:
            run_id = S3Parser._parse_value(message_body, 'run_id')
            run_id = int(run_id)
        except:
            return reply
        try:
            to = S3Parser._parse_value(message_body, 'reply_to')
        except:
            return reply
        now = datetime.datetime.utcnow().isoformat()
        subject = 'MONITOR    REPLY:    Mail    Received    and    Parsed    OK'
        message = ('Test    message    sent    to    %s    from    :run_id:%s:    arrived    fine    &    was    parsed    at    %s.' % (current.deployment_settings.get_base_public_url(), run_id, now))
        result = current.msg.send_email(to, subject, message)
        return reply
    elif (':mission_id:' in message_body):
        pass
    else:
        return reply
    try:
        mission_id = S3Parser._parse_value(message_body, 'mission_id')
        mission_id = int(mission_id)
    except:
        return reply
    data = dict(message_id=message_id, mission_id=mission_id)
    person_id = S3Parsing().lookup_person(message.from_address)
    if person_id:
        atable = s3db.deploy_application
        htable = s3db.hrm_human_resource
        left = atable.on((htable.id == atable.human_resource_id))
        rows = db(((htable.person_id == person_id) & (htable.deleted != True))).select(htable.id, atable.id, atable.active, orderby=(~ htable.modified_on), left=left)
        hr_id = None
        if (len(rows) == 1):
            hr_id = rows[0][htable.id]
        else:
            rows = [row for row in rows if (row[atable.id] and row[atable.active])]
            if (len(rows) == 1):
                hr_id = rows[0][htable.id]
        if hr_id:
            data['human_resource_id'] = hr_id
    table = s3db.deploy_response
    table.insert(**data)
    atable = s3db.msg_attachment
    atts = db((atable.message_id == message_id)).select(atable.document_id)
    if atts:
        dtable = db.doc_document
        ltable = s3db.deploy_mission_document
        if hr_id:
            hrtable = db.hrm_human_resource
            doc_id = db((hrtable.id == hr_id)).select(hrtable.doc_id, limitby=(0, 1)).first().doc_id
        for row in atts:
            document_id = row.document_id
            ltable.insert(mission_id=mission_id, message_id=message_id, document_id=document_id)
            if hr_id:
                db((dtable.id == document_id)).update(doc_id=doc_id)
    return reply
