# Generated from java by J2P
from __future__ import annotations
from geniusweb.actions.Action import Action
from geniusweb.connection.ConnectionEnd import ConnectionEnd
from geniusweb.inform.Inform import Inform
from geniusweb.party.Party import Party
from tudelft.utilities.listener.Listener import Listener
from tudelft_utilities_logging.ReportToFile import ReportToFile
from tudelft_utilities_logging.Reporter import Reporter
from typing import Optional
import tempfile


class DefaultParty(Party, Listener[Inform]):
 '''
 Party with default implementation to handle the connection.
 

 '''
 
 def __init__(self):
  '''
  Creates new party, setting reporter to a file with the class name in the
  temp directory. This default is to avoid parties printing to stdout,
  which is confusing (eg when this happens on a server) and even fatal (if
  the party is a python party running in a PyRunner). It is highly
  recommended that {@link #setReporter(Reporter)} is called immediately and
  that noghing is logged until after that.

  '''
  self.__connection:Optional[ConnectionEnd[Inform,Action]] = None
  self._reporter:Reporter = None
  super().__init__()
  try:
   self._reporter=ReportToFile(tempfile.NamedTemporaryFile(prefix=type(self).__name__, suffix=".log").name)
  except IOError as e:
   raise BaseException("Failed to create log file for new party") from e
 
 def setReporter(self,reporter:Reporter) -> Optional[Party]:
  '''
  Set the reporter. If needed, use immediately after constructing. This is
  mainly used for debugging and tests.

  '''
  if (reporter is None):
   raise ValueError("reporter must be not null")
  self._reporter=reporter
  return self
 
 #Override
 def connect(self,connection:ConnectionEnd[Inform,Action]) -> None:
  self.__connection=connection
  connection.addListener(self)
 
 #Override
 def disconnect(self) -> None:
  if (self.__connection is not None):
   self.__connection.removeListener(self)
   self.__connection.close()
   self.__connection=None
 
 #Override
 def terminate(self) -> None:
  self.disconnect()
 
 def getConnection(self) -> Optional[ConnectionEnd[Optional[Inform],Optional[Action]]]:
  '''
  @return currently available connection, or null if not currently
          connected.

  '''
  return self.__connection
 
 def getReporter(self) -> Reporter:
  return self._reporter
