# Path: groundstation/settings.py
# PORT=1248 # Port to listen on (udp+tcp)
# BEACON_TIMEOUT=5 # 5 second timeout between beacons
# DEFAULT_BUFSIZE=8192 # 8k bytes
# DEFAULT_CACHE_LIFETIME=30 # 30 Seconds
# STORAGE_BACKEND="git"
# LISTALLOBJECTS_CHUNK_THRESHOLD=1024
# LISTALLCHANNELS_RETRY_TIMEOUT=5
# CLOSEWAIT_TIMEOUT=240 # 2MSL
# 
# Path: groundstation/transfer/response.py
# class Response(object):
#     def __init__(self, response_to, verb, payload, station=None, stream=None, origin=None):
#         self.type = "RESPONSE"
#         self.id = response_to
#         self.station = station
#         self.stream = stream
#         self.verb = verb
#         self.payload = payload
#         # if origin:
#         #     self.origin = uuid.UUID(origin)
#         self.origin = origin
# 
#     def _Request(self, *args, **kwargs):
#         kwargs['station'] = self.station
#         req = groundstation.transfer.request.Request(*args, **kwargs)
#         self.station.register_request(req)
#         return req
# 
#     @classmethod
#     def from_gizmo(klass, gizmo, station, stream):
#         log.debug("Hydrating a response from gizmo")
#         return Response(gizmo.id, gizmo.verb, gizmo.payload, station, stream, gizmo.stationid)
# 
#     def SerializeToString(self):
#         gizmo = self.station.gizmo_factory.gizmo()
#         gizmo.id = str(self.id)
#         gizmo.type = Gizmo.RESPONSE
#         gizmo.verb = self.verb
#         if self.payload:
#             gizmo.payload = self.payload
#         return gizmo.SerializeToString()
# 
#     def process(self):
#         if self.verb not in self.VALID_RESPONSES:
#             raise Exception("Invalid Response verb: %s" % (self.verb))
# 
#         self.VALID_RESPONSES[self.verb](self)
# 
#     VALID_RESPONSES = {
#             "TRANSFER": response_handlers.handle_transfer,
#             "DESCRIBEOBJECTS": response_handlers.handle_describeobjects,
#             "DESCRIBECHANNELS": response_handlers.handle_describechannels,
#             "TERMINATE": response_handlers.handle_terminate,
#     }
# 
#     @property
#     def payload(self):
#         return self._payload
#     @payload.setter
#     def payload(self, value):
#         self._payload = str(value)


import socket
import errno
import groundstation.logger
from groundstation import settings
from groundstation.transfer.response import Response
from socket_closed_exception import SocketClosedException

log = groundstation.logger.getLogger(__name__)

class StreamSocket(object):
    """Base class for conversational protocols

    If you don't want a socket allocated (ie, you already have one) set it to
    ._sock before calling __init__"""
    def __init__(self):
        if not hasattr(self, "_sock"):
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # XXX Implement the queue as a seperate class/
        self.write_queue = []
        self.packet_queue = []
        self.buffer = ""

    def fileno(self):
        return self.socket.fileno()

    @property
    def socket(self):
        return self._sock

    def accept(self, klass):
        p = self._sock.accept()
        log.info("Accepted a connection from %s" % repr(p[1]))
        # Return more instances of ourself.
        return klass.from_accept(p)


# Path: groundstation/settings.py
# PORT=1248 # Port to listen on (udp+tcp)
# BEACON_TIMEOUT=5 # 5 second timeout between beacons
# DEFAULT_BUFSIZE=8192 # 8k bytes
# DEFAULT_CACHE_LIFETIME=30 # 30 Seconds
# STORAGE_BACKEND="git"
# LISTALLOBJECTS_CHUNK_THRESHOLD=1024
# LISTALLCHANNELS_RETRY_TIMEOUT=5
# CLOSEWAIT_TIMEOUT=240 # 2MSL
# 
# Path: groundstation/transfer/response.py
# class Response(object):
#     def __init__(self, response_to, verb, payload, station=None, stream=None, origin=None):
#         self.type = "RESPONSE"
#         self.id = response_to
#         self.station = station
#         self.stream = stream
#         self.verb = verb
#         self.payload = payload
#         # if origin:
#         #     self.origin = uuid.UUID(origin)
#         self.origin = origin
# 
#     def _Request(self, *args, **kwargs):
#         kwargs['station'] = self.station
#         req = groundstation.transfer.request.Request(*args, **kwargs)
#         self.station.register_request(req)
#         return req
# 
#     @classmethod
#     def from_gizmo(klass, gizmo, station, stream):
#         log.debug("Hydrating a response from gizmo")
#         return Response(gizmo.id, gizmo.verb, gizmo.payload, station, stream, gizmo.stationid)
# 
#     def SerializeToString(self):
#         gizmo = self.station.gizmo_factory.gizmo()
#         gizmo.id = str(self.id)
#         gizmo.type = Gizmo.RESPONSE
#         gizmo.verb = self.verb
#         if self.payload:
#             gizmo.payload = self.payload
#         return gizmo.SerializeToString()
# 
#     def process(self):
#         if self.verb not in self.VALID_RESPONSES:
#             raise Exception("Invalid Response verb: %s" % (self.verb))
# 
#         self.VALID_RESPONSES[self.verb](self)
# 
#     VALID_RESPONSES = {
#             "TRANSFER": response_handlers.handle_transfer,
#             "DESCRIBEOBJECTS": response_handlers.handle_describeobjects,
#             "DESCRIBECHANNELS": response_handlers.handle_describechannels,
#             "TERMINATE": response_handlers.handle_terminate,
#     }
# 
#     @property
#     def payload(self):
#         return self._payload
#     @payload.setter
#     def payload(self, value):
#         self._payload = str(value)


# Path: groundstation/sockets/stream_socket.py
import socket
import errno
import groundstation.logger
from groundstation import settings
from groundstation.transfer.response import Response
from socket_closed_exception import SocketClosedException


log = groundstation.logger.getLogger(__name__)

class StreamSocket(object):
    """Base class for conversational protocols

    If you don't want a socket allocated (ie, you already have one) set it to
    ._sock before calling __init__"""
    def __init__(self):
        if not hasattr(self, "_sock"):
            self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # XXX Implement the queue as a seperate class/
        self.write_queue = []
        self.packet_queue = []
        self.buffer = ""

    def fileno(self):
        return self.socket.fileno()

    @property
    def socket(self):
        return self._sock

    def accept(self, klass):
        p = self._sock.accept()
        log.info("Accepted a connection from %s" % repr(p[1]))
        # Return more instances of ourself.
        return klass.from_accept(p)


    def enqueue(self, data):