# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8

"""
   This file parses messages using functions defined in in the template's
   parser.py

   @copyright: 2012-15 (c) Sahana Software Foundation
   @license: MIT

   Permission is hereby granted, free of charge, to any person
   obtaining a copy of this software and associated documentation
   files (the "Software"), to deal in the Software without
   restriction, including without limitation the rights to use,
   copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the
   Software is furnished to do so, subject to the following
   conditions:

   The above copyright notice and this permission notice shall be
   included in all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
   NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
   HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
   WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
   OTHER DEALINGS IN THE SOFTWARE.
"""

__all__ = ("S3Parsing",)

import sys

from gluon import current

# =============================================================================
class S3Parsing(object):
    """
       Core Message Parsing Framework
       - reusable functions
    """

    # -------------------------------------------------------------------------
    @staticmethod
    def parser(function_name, message_id, **kwargs):
        """
           1st Stage Parser
           - called by msg.parse()

           Sets the appropriate Authorisation level and then calls the
           parser function from the template
        """

        reply = None
        s3db = current.s3db

        # Retrieve Message
        table = s3db.msg_message
        message = current.db(table.message_id == message_id).select(limitby=(0, 1)
                                                                    ).first()

        from_address = message.from_address
        if "<" in from_address:
            from_address = from_address.split("<")[1].split(">")[0]
        email = S3Parsing.is_session_alive(from_address)