#######################################################
# 
# ReceiveConnections.py
# Python implementation of the Class ReceiveConnections
# Generated by Enterprise Architect
# Created on:      19-May-2020 6:21:05 PM
# Original author: Natha Paquette
# 
#######################################################
import socket
import time
from logging.handlers import RotatingFileHandler
import logging
from FreeTAKServer.controllers.configuration.LoggingConstants import LoggingConstants
import sys
from FreeTAKServer.controllers.model.RawConnectionInformation import RawConnectionInformation
from FreeTAKServer.controllers.CreateLoggerController import CreateLoggerController
from FreeTAKServer.controllers.configuration.ReceiveConnectionsConstants import ReceiveConnectionsConstants
loggingConstants = LoggingConstants()
logger = CreateLoggerController("ReceiveConnections").getLogger()
#TODO: move health check values to constants and create controller for HealthCheck data

class ReceiveConnections:
    def __init__(self):
        pass


    def listen(self, sock):
        #logger = CreateLoggerController("ReceiveConnections").getLogger()
        #listen for client connections
        sock.listen(0)
        try:
            #establish the socket variables
            client, address = sock.accept()
            #wait to receive client
            client.settimeout(int(ReceiveConnectionsConstants().RECEIVECONNECTIONDATATIMEOUT))
            data = client.recv(1024)
            client.settimeout(0)
            logger.info(loggingConstants.RECEIVECONNECTIONSLISTENINFO)
            #establish the socket array containing important information about the client
            m_RawConnectionInformation = RawConnectionInformation()
            m_RawConnectionInformation.ip = address
            m_RawConnectionInformation.socket = client
            m_RawConnectionInformation.xmlString = data.decode('utf-8')
            try:
                if socket != None and data != b'':
                    return m_RawConnectionInformation
                else:
                    return -1
            except Exception as e:
                logger.error('exception in returning data '+str(e))
                return -1

        except Exception as e:
            logger.error(loggingConstants.RECEIVECONNECTIONSLISTENERROR+str(e))
            return -1
