#!/usr/bin/env python3.2
#
# Copyright (c) Net24 Limited, Christchurch, New Zealand 2011-2012
#       and     Voyager Internet Ltd, New Zealand, 2012-2013
#
#    This file is part of py-magcode-core.
#
#    Py-magcode-core is free software: you can redistribute it and/or modify
#    it under the terms of the GNU  General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    Py-magcode-core is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU  General Public License for more details.
#
#    You should have received a copy of the GNU  General Public License
#    along with py-magcode-core.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Event queue module  


Implents a python event queue against a SQL database table, using SQLALchemy.
"""

import sys
import os
import time
import threading
import json
import signal
from queue import Queue
from queue import Empty
from copy import copy
from traceback import format_exc

from sqlalchemy import Table
from sqlalchemy import MetaData
from sqlalchemy.orm import mapper
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm import scoped_session
from sqlalchemy.orm.session import make_transient
from sqlalchemy.sql.expression import func
from sqlalchemy.sql import text
from sqlalchemy.exc import DBAPIError
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm.exc import NoResultFound

from magcode.core import *
from magcode.core.utility import send_signal
from magcode.core.utility import get_numeric_setting
from magcode.core.database import *


# some state static constant
ESTATE_NEW = 'NEW'
ESTATE_RETRY = 'RETRY'
ESTATE_SUCCESS = 'SUCCESS'
ESTATE_FAILURE = 'FAILURE'
event_process_states = frozenset((ESTATE_NEW,ESTATE_RETRY))
event_processed_states = frozenset((ESTATE_SUCCESS, ESTATE_FAILURE))
event_states = event_process_states.union(event_processed_states)

# Lists we use in global sql_data dict
sql_data['event_subclasses'] = []
sql_data['event_type_list'] = []


def eventregister(class_):
    """
    Event descedant class decorator function to register class for SQL
    A
lchemy mapping in init_event_class() below, called in 
    magcode.core.database.utility.setup_sqlalchemy()
    """
    sql_data['event_subclasses'].append(class_)
    sql_data['event_type_list'].append(class_.__name__)
    sql_data['events'][class_.__name__] = class_
    return(class_)

def sync
eventregister(class_):
    """
    Event descedant class decorator function to register class for SQL
    Alchemy mapping in init_event_class() below, called in 
    magcode.core.database.utility.setup_sqlalchemy()
    This one is for SyncEvent classes.
    """
    sql_data['event_subclasses'].append(class_)
    sql_data['events'][class_.__name__] = class_
    return(class_)

class EventAlreadyProcessing(Exception):
    """
    Event already processing
    """

class QueueReset(Exception):
    """
    Queue reset as DB connection loss detected
    """

class _EQueue(Queue):
    """
    Internal queue class with dictionary of events being processed

    This replaces methods on Queue so that processing array is only altered
    when mutex held to prevent races.
    """
    def __init__(self):
        """
        Special init to set queue size
        """
        self.processing = {}
        self.queue_reset = False
        super().__init__(
                maxsize=get_numeric_setting('event_queue_maxsize', int))

    def _put(self, item):
        """
        Put an event on the Queue, and record it as being processed.
        """
        if self.queue_reset:
            raise QueueReset("Event queue reset")
        if self.processing.get(item.id_):
            raise EventAlreadyProcessing("Event '%s' is already processing."
                         % item.id_)
        self.processing[item.id_] = True
        super()._put(item)

    def start_queue_reset(self):
        self.queue_reset = True
        while True:
            try:
                event = super().get_nowait()
                super().task_done()
            except Empty: 
                break

    def is_queue_reseting(self):
        return self.queue_reset

    def clean_up(self):
        """
        Cleans up after queue emptied.
        """
        self.join()
        self.queue_reset = False
        self.processing = {}

    def task_done(self, event_id):
        """
        task done
        """
        if event_id:
            self.processing.pop(event_id)
        super().task_done()



class EventProcess(object):
    """
    Container class for event processing methods for an event.
    These are both used by queued events and synchronous events.
    """
    def _failure_results(self, db_session, reason, 
            function="event_process_wrapper" ):
        self.state = ESTATE_FAILURE
        self.result_code = RCODE_FATAL
        self.processed = db_time(db_session)
        self._clean_attrs()
        log_error("%s() - FAILING event id: '%s', "
                   "event_type: '%s', state: '%s', scheduled '%s',"
                   " created: '%s', processed: '%s' with result "
                   "'%s - %s, %s' - %s"  
                   % (function, self.id_, self.event_type, self.state,
                                self.scheduled, self.created,
                                self.processed, 
                                self.result_code,
                                result_code_dict[self.result_code],
                                result_code_lstr_dict[self.result_code],
                                reason))
        return

    def _clean_attrs(self):
        """
        Clean off attrs we don't want so event can go to DB without
        giving SQLAlchemy a headache.
        """
        if hasattr(self, 'db_session'):
            delattr(self, 'db_session')
        if hasattr(self, 'py_results'):
            delattr(self, 'py_results')
        if hasattr(self, 'py_parameters'):
            delattr(self, 'py_parameters')
        
    def _process_wrapper(self, db_session):
        """
        Setup and teardown method that wraps the 
        events process() method.

        Sets up environment, sets fields once process() finished
        and does other janitorial work.  In here rather that in 
        Event class to make Event code tidy.
        """

        # Safe guard to see if we are already processed
        if (self.state not in event_process_states):
            return

        # Set up dyanmic data for this event
        self.db_session = db_session
        # Set up results as an empty dictionary - easy for events to insert
        # results, message etc.
        self.py_results = {}

        if (self.parameters):
            # JSON decode parameters
            try:
                self.py_parameters = json.loads(self.parameters)
            except Exception:
                self._failure_results(db_session,
                        "could not decode JSON parameters.")
                return
        else:
            py_parameters = None

        # Call event state machine
        log_debug("_process_wrapper() - processing event id: '%s', "
                       "event_type: '%s', state: '%s', scheduled '%s',"
                       " created: '%s'" 
                       % (self.id_, self.event_type, self.state,
                                    self.scheduled, self.created))
        
        result_code = self.process()
        self.result_code = result_code

        # JSON encode results
        if (self.py_results):
            try:
                self.results = json.dumps(self.py_results)
            except Exception:
                self._failure_results(db_session,
                            "could not encode JSON results.")
                return

        # Check returned result code is sensible
        if (result_code not in result_codes):
            self._failure_results(db_session, 
                        "result code not recognised.")
            return
        