# Path: elevator_cli/io.py
# def output_result(status, result, *args, **kwargs):
#     if result:
#         if status == FAILURE_STATUS:
#             puts(colored.red(str(result)))
#         else:
#             puts(str(result))
# 
# Path: elevator_cli/helpers.py
# def success(datas):
#     return SUCCESS_STATUS, datas
# 
# def fail(type, msg):
#     return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg])
# 
# Path: elevator_cli/message.py
# class Request(object):
#     """Handler objects for frontend->backend objects messages"""
#     def __new__(cls, *args, **kwargs):
#         try:
#             content = {
#                 'meta': kwargs.pop('meta', {}),
#                 'uid': kwargs.get('db_uid'),  # uid can eventually be None
#                 'cmd': kwargs.pop('command'),
#                 'args': kwargs.pop('args'),
#             }
#         except KeyError:
#             raise MessageFormatError("Invalid request format : %s" % str(kwargs))
# 
#         return msgpack.packb(content)
# 
# class ResponseHeader(object):
#     def __init__(self, raw_header):
#         header = msgpack.unpackb(raw_header)
# 
#         try:
#             self.status = header.pop('status')
#             self.err_code = header.pop('err_code')
#             self.err_msg = header.pop('err_msg')
#         except KeyError:
#             errors_logger.exception("Invalid response header : %s" %
#                                     header)
#             raise MessageFormatError("Invalid response header")
# 
#         for key, value in header.iteritems():
#             setattr(self, key, value)
# 
# class Response(object):
#     def __init__(self, raw_message, *args, **kwargs):
#         message = msgpack.unpackb(raw_message)
# 
#         try:
#             self.datas = message['datas']
#         except KeyError:
#             errors_logger.exception("Invalid response message : %s" %
#                                     message)
#             raise MessageFormatError("Invalid response message")


import zmq
from elevator.constants import *
from .io import output_result
from .errors import *
from .helpers import success, fail
from .message import Request, ResponseHeader, Response

    def teardown_socket(self):
        self.socket.close()
        self.context.term()

    def _process_request(self, command, arguments):
        if command in ["MGET"] and arguments:
            return command, [arguments]
        return command, arguments

    def _process_response(self, req_cmd, res_datas):
        if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas:
            return res_datas[0]
        return res_datas

    def send_cmd(self, db_uid, command, arguments, *args, **kwargs):
        command, arguments = self._process_request(command, arguments)
        self.socket.send_multipart([Request(db_uid=db_uid,
                                                             command=command,
                                                             args=arguments,
                                                             meta={})],)

        try:
            raw_header, raw_response = self.socket.recv_multipart()
            header = ResponseHeader(raw_header)
            response = Response(raw_response)

            if header.status == FAILURE_STATUS:
                return fail(ELEVATOR_ERROR[header.err_code], header.err_msg)
        except zmq.core.error.ZMQError:

# Path: elevator_cli/io.py
# def output_result(status, result, *args, **kwargs):
#     if result:
#         if status == FAILURE_STATUS:
#             puts(colored.red(str(result)))
#         else:
#             puts(str(result))
# 
# Path: elevator_cli/helpers.py
# def success(datas):
#     return SUCCESS_STATUS, datas
# 
# def fail(type, msg):
#     return FAILURE_STATUS, "Error : " + ', '.join([type.upper(), msg])
# 
# Path: elevator_cli/message.py
# class Request(object):
#     """Handler objects for frontend->backend objects messages"""
#     def __new__(cls, *args, **kwargs):
#         try:
#             content = {
#                 'meta': kwargs.pop('meta', {}),
#                 'uid': kwargs.get('db_uid'),  # uid can eventually be None
#                 'cmd': kwargs.pop('command'),
#                 'args': kwargs.pop('args'),
#             }
#         except KeyError:
#             raise MessageFormatError("Invalid request format : %s" % str(kwargs))
# 
#         return msgpack.packb(content)
# 
# class ResponseHeader(object):
#     def __init__(self, raw_header):
#         header = msgpack.unpackb(raw_header)
# 
#         try:
#             self.status = header.pop('status')
#             self.err_code = header.pop('err_code')
#             self.err_msg = header.pop('err_msg')
#         except KeyError:
#             errors_logger.exception("Invalid response header : %s" %
#                                     header)
#             raise MessageFormatError("Invalid response header")
# 
#         for key, value in header.iteritems():
#             setattr(self, key, value)
# 
# class Response(object):
#     def __init__(self, raw_message, *args, **kwargs):
#         message = msgpack.unpackb(raw_message)
# 
#         try:
#             self.datas = message['datas']
#         except KeyError:
#             errors_logger.exception("Invalid response message : %s" %
#                                     message)
#             raise MessageFormatError("Invalid response message")


# Path: elevator_cli/client.py
import zmq
from elevator.constants import *
from .io import output_result
from .errors import *
from .helpers import success, fail
from .message import Request, ResponseHeader, Response


    def teardown_socket(self):
        self.socket.close()
        self.context.term()

    def _process_request(self, command, arguments):
        if command in ["MGET"] and arguments:
            return command, [arguments]
        return command, arguments

    def _process_response(self, req_cmd, res_datas):
        if req_cmd in ["GET", "DBCONNECT", "PING"] and res_datas:
            return res_datas[0]
        return res_datas

    def send_cmd(self, db_uid, command, arguments, *args, **kwargs):
        command, arguments = self._process_request(command, arguments)
        self.socket.send_multipart([Request(db_uid=db_uid,
                                                             command=command,
                                                             args=arguments,
                                                             meta={})],)

        try:
            raw_header, raw_response = self.socket.recv_multipart()
            header = ResponseHeader(raw_header)
            response = Response(raw_response)

            if header.status == FAILURE_STATUS:
                return fail(ELEVATOR_ERROR[header.err_code], header.err_msg)
        except zmq.core.error.ZMQError:

            return fail("TimeoutError", "Server did not respond in time")