###########################################################################
# Copyright (c) 2018- Franco (nextime) Lanza <franco@nexlab.it>
#
# Penguidom System client Daemon "penguidomd"  [https://git.nexlab.net/domotika/Penguidom]
#
# This file is part of penguidom.
#
# penguidom 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.
#
# 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, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from nexlibs.singleton import Singleton
from twisted.internet import reactor


EXPIRETIME=300

class MessengerLinksSingleton(Singleton):


   links = {}
   expires = {}

   def __init__(self, *args, **kwargs):
      Singleton.__init__( self )

   def del_expire(self, linkid):
      if linkid in self.expires.keys():
         try:
            self.expires[linkid].cancel()
         except:
            pass
         del self.expires[linkid]


   def add_expire(self, linkid):
      self.del_expire(linkid)
      self.expires[linkid] = reactor.callLater(EXPIRETIME, self.del_link, linkid)  

   def add_link(self, linkid, usr):
      self.links[linkid] = usr;
      self.add_expire(linkid)

   def del_link(self, linkid):
      if linkid in self.links.keys():
         del self.links[linkid]

   def get_link(self, linkid):
      if linkid in self.links.keys():
         return self.links[linkid]
      return False

   def linkid_exists(self, linkid):
      if linkid in self.links.keys():
         return True
      return False


def MessengerLinkRegistry():
   return MessengerLinksSingleton.getInstance()


class MessengerPSIDSingleton(Singleton):

   links = {}
   def __init__(self, *args, **kwargs):
      Singleton.__init__( self )

   def add_link(self, linkid, usr):
      self.links[linkid] = usr;
      
   def del_link(self, linkid):
      if linkid in self.links.keys():
         del self.links[linkid]
         
   def get_link(self, linkid):
      if linkid in self.links.keys():
         return self.links[linkid]
      return False
      
   def linkid_exists(self, linkid):
      if linkid in self.links.keys():
         return True
      return False

def MessengerPSIDRegistry():
   return MessengerPSIDSingleton.getInstance()