# Path: groundstation/proto/git_object_pb2.py
# class GitObject(_message.Message):
#   __metaclass__ = _reflection.GeneratedProtocolMessageType
#   DESCRIPTOR = _GITOBJECT
# 
#   # @@protoc_insertion_point(class_scope:GitObject)
# 
# Path: groundstation/logger.py
#     LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG"))
#     LEVEL = logging.DEBUG
# CONSOLE_FORMATTER = _get_formatter()
# CONSOLE_HANDLER = _get_console_handler()
# LOGGERS = {}  # Cache for instanciated loggers
# def fix_oid(oid):
# def _get_formatter():
# def _get_console_handler():
# def getLogger(name):  # Not threadsafe


import pygit2
import groundstation.utils as utils
from groundstation.proto.git_object_pb2 import GitObject
from groundstation import logger

log = logger.getLogger(__name__)


class UnsolicitedTransfer(Exception):
    pass


def handle_transfer(self):
    git_pb = GitObject()
    git_pb.ParseFromString(self.payload)
    log.info("Handling TRANSFER of %s" % (git_pb.type))

    try:
        req = self.station.get_request(self.id)
    except KeyError:
        raise UnsolicitedTransfer

    if git_pb.type == pygit2.GIT_OBJ_BLOB:
        data_hash = utils.oid2hex(pygit2.hash(git_pb.data))
        assert req.payload == data_hash, \
            "Attempted to be sent invalid object for %s; got %s" % (req.payload, data_hash)
    ret = self.station.store.write(git_pb.type, git_pb.data)

# Path: groundstation/proto/git_object_pb2.py
# class GitObject(_message.Message):
#   __metaclass__ = _reflection.GeneratedProtocolMessageType
#   DESCRIPTOR = _GITOBJECT
# 
#   # @@protoc_insertion_point(class_scope:GitObject)
# 
# Path: groundstation/logger.py
#     LEVEL = getattr(logging, os.getenv("GROUNDSTATION_DEBUG"))
#     LEVEL = logging.DEBUG
# CONSOLE_FORMATTER = _get_formatter()
# CONSOLE_HANDLER = _get_console_handler()
# LOGGERS = {}  # Cache for instanciated loggers
# def fix_oid(oid):
# def _get_formatter():
# def _get_console_handler():
# def getLogger(name):  # Not threadsafe


# Path: groundstation/transfer/response_handlers/transfer.py
import pygit2
import groundstation.utils as utils
from groundstation.proto.git_object_pb2 import GitObject
from groundstation import logger


log = logger.getLogger(__name__)


class UnsolicitedTransfer(Exception):
    pass


def handle_transfer(self):
    git_pb = GitObject()
    git_pb.ParseFromString(self.payload)
    log.info("Handling TRANSFER of %s" % (git_pb.type))

    try:
        req = self.station.get_request(self.id)
    except KeyError:
        raise UnsolicitedTransfer

    if git_pb.type == pygit2.GIT_OBJ_BLOB:
        data_hash = utils.oid2hex(pygit2.hash(git_pb.data))
        assert req.payload == data_hash, \
            "Attempted to be sent invalid object for %s; got %s" % (req.payload, data_hash)
    ret = self.station.store.write(git_pb.type, git_pb.data)

    log.info("Wrote object %s into local db" % logger.fix_oid(ret))