from socket import gaierror
import cqi
from app import socketio
from app.decorators import socketio_login_required
from . import NAMESPACE as ns
from .utils import cqi_over_socketio


@socketio.on('cqi.connect', namespace=ns)
@socketio_login_required
@cqi_over_socketio
def cqi_connect(cqi_client: cqi.CQiClient):
    try:
        cqi_status = cqi_client.connect()
    except gaierror as e:
        return {
            'code': 500,
            'msg': 'Internal Server Error',
            'payload': {'code': e.args[0], 'desc': e.args[1]}
        }
    payload = {'code': cqi_status,
               'msg': cqi.api.specification.lookup[cqi_status]}
    return {'code': 200, 'msg': 'OK', 'payload': payload}


@socketio.on('cqi.disconnect', namespace=ns)
@socketio_login_required
@cqi_over_socketio
def cqi_disconnect(cqi_client: cqi.CQiClient):
    cqi_status = cqi_client.disconnect()
    payload = {'code': cqi_status,
               'msg': cqi.api.specification.lookup[cqi_status]}
    return {'code': 200, 'msg': 'OK', 'payload': payload}


@socketio.on('cqi.ping', namespace=ns)
@socketio_login_required
@cqi_over_socketio
def cqi_ping(cqi_client: cqi.CQiClient):
    cqi_status = cqi_client.ping()
    payload = {'code': cqi_status,
               'msg': cqi.api.specification.lookup[cqi_status]}
    return {'code': 200, 'msg': 'OK', 'payload': payload}
