from uuid import uuid4

import pendulum

from pot_libs.aiomqtt_util.hbmqtt_utils import MqttUtil
from pot_libs.sanic_api import summary
from unify_api.modules.device_cloud.components.command import GcReq, \
    ChangeConfigReqV2, CommandV2Request, GdsReq, GetConfigRequest
from unify_api.modules.device_cloud.components.common import BaseResponse


async def _query_device(body):
    data = body.to_dict()

    request_id = str(uuid4())
    data["request_id"] = request_id
    data["time"] = pendulum.now().to_datetime_string()
    try:
        async with MqttUtil() as emq:
            result = await emq.device_response(
                body.sid, request_id, data
            )
            return BaseResponse(**result)
    except TimeoutError:
        return BaseResponse(request_id, 408, 'timeout'), 408


@summary('下发配置')
async def post_change_config(req, body: ChangeConfigReqV2) -> BaseResponse:
    return await _query_device(body)


@summary("下发命令")
async def post_command(req, body: CommandV2Request) -> BaseResponse:
    return await _query_device(body)


@summary("配置查看")
async def post_get_config(req, body: GcReq) -> BaseResponse:
    return await _query_device(body)


@summary("配置查看V1.0")
async def post_get_config_v1(req, body: GetConfigRequest) -> BaseResponse:
    return await _query_device(body)


@summary("装置状态查看")
async def post_get_device_status(req, body: GdsReq) -> BaseResponse:
    return await _query_device(body)