# Copyright (c) 2001 LOGILAB S.A. (Paris, FRANCE).
# http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This program 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 2 of the License, or (at your option) any later
# version.
#
# This program 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
# this program; if not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA  02111-1307
# USA.

"""
EngineController
"""

__revision__ = "$Id: EngineController.py,v 1.14 2002/01/28 11:27:51 syt Exp $"

from narval.PlanListener import *
from narval.MemoryListener import *
from narval.EngineListener import *
from EngineModel import EngineModel
from narval.gui import unicode_to_gtk

class EngineController(EngineListenerInterface, MemoryListenerInterface,
                       PlanListenerInterface):
    """
    Controller of engine matching part
    Use borg pattern
    """

    _DICT = {}

    def __init__(self):
        self.__dict__ = self._DICT
        self._logfile = None

    # Implement EngineListener Interface ######################################
    ## queue event
    def postQueueEvent(self,evtId,text):
        EngineModel().event_queue_append(evtId)
        EngineModel().event_queue_messages_append(evtId,(text,0))
        
    def popQueueEvent(self,evtId):
        try:
            EngineModel().event_queue_messages_append(\
                evtId,(EngineModel().get_event_queue_messages()[evtId][0],1))
        except:
            print unicode_to_gtk(_('No such event in eventQueue:')), evtId

    ## scheduler event
    def postSchedulerEvent(self,evtId,text):
        EngineModel().scheduler_queue_append(evtId)
        EngineModel().scheduler_queue_messages_append(evtId,(text,0))
        
    def popSchedulerEvent(self,evtId):
        try:
            EngineModel().scheduler_queue_messages_append(\
                evtId,(EngineModel().get_scheduler_queue_messages()[evtId][0],1))
        except:
            print unicode_to_gtk(_('No such event in schedulerQueue:')), evtId

    ## clean functions
    def clean_event(self):
        EngineModel().clean_event()

    def clean_scheduler(self):
        EngineModel().clean_scheduler()

    def clean_messages(self):
        EngineModel().clean_messages()


    # implement PlanListener Interface #########################################
    
    def fireTransition(self,planId,transitionId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Plan %s firing transition %s\n")%(planId,transitionId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Plan %s firing transition %s\n")%(planId,transitionId)))

    def transitionStatusChanged(self,planId,transitionId,status):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Plan %s transition %s changed to %s\n")%
                (planId,transitionId,status)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Plan %s transition %s changed to %s\n")%
                (planId,transitionId,status)))

    def stepStatusChanged(self,planId,stepId,status):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Plan %s step %s changed to %s\n")%(planId,stepId,status)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Plan %s step %s changed to %s\n")%(planId,stepId,status)))

    def planStatusChanged(self,planId,status):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Plan %s changed to %s\n")%(planId,status)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Plan %s changed to %s\n")%(planId,status)))

    def instanciateRecipe(self,planId,recipeName):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("New plan %s made from recipe %s\n")%(planId,recipeName)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("New plan %s made from recipe %s\n")%(planId,recipeName)))

    def planAddElement(self,planId,elementId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Added element %s to Plan %s\n")%(elementId,planId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Added element %s to Plan %s\n")%(elementId,planId)))
        
    def planRemoveElement(self,planId,elementId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Removed element %s from Plan %s\n")%(elementId,planId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Removed element %s from Plan %s\n")%(elementId,planId)))

    # implement MemoryListener Interface ######################################
    
    def addElement(self,elementId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Added element %s to memory\n")%(elementId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Added element %s to memory\n")%(elementId)))

    def removeElement(self,elementId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Removed element %s from memory\n")%(elementId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Removed element %s from memory\n")%(elementId)))

    def replaceElement(self,elementId):
        if self._logfile:
            self._append_log(unicode_to_gtk(
                _("Replaced element %s in memory\n")%(elementId)))
        else:
            EngineModel().messages_list_append(unicode_to_gtk(
                _("Replaced element %s in memory\n")%(elementId)))

    # start a new log file from CLI ###########################################
    def open_logfile(self):
        import time
        from socket import gethostname
        # create a new log file
        tps = time.localtime(time.time())
        date = time.strftime("%y%m%d-%Hh%Mm%S",tps)
        name = './messages-from-narval-%s-%s.xml' % (gethostname(), date)
        print name
        self._log_file = open(name,'w')
        self._append_log(log,'<!-- Report created %s -->\n' % time.asctime(tps))

    def close_logfile(self):
        if self._logfile is not None:
            self._logfile.close()
        self._logfile = None

    # Private #################################################################
    def _append_log(self, txt):
        if self._logfile:
            self._logfile.write(txt)
            self._logfile.flush()
