import json

from flask import request

from app.extensions.utils.time_helper import get_str_from_today
from app.http.requests.v1.iot_request import CreateReceiveDataRequestSchema
from app.http.responses.presenters.v1.iot_presenter import (
    CreateReceiveDataPresenter,
    FailureReceiveDataPresenter,
)
from app.http.view import api
from core.domains.iot.dto.iot_dto import FailureReceiveDataDto
from core.domains.iot.use_case.v1.iot_use_case import (
    CreateReceiveDataUseCase,
    FailureReceiveDataUseCase,
)


@api.route("/v1/iot/receive", methods=["POST"])
def create_receive_data_view():
    try:
        dto = CreateReceiveDataRequestSchema(
            **request.form.to_dict()
        ).validate_request_and_make_dto()

        return CreateReceiveDataPresenter().transform(
            CreateReceiveDataUseCase().execute(dto=dto)
        )
    except Exception as e:
        dto = FailureReceiveDataDto(
            sensormac=request.form.get("sensormac"),
            receive_data=json.dumps(request.form.to_dict()),
            reason=str(e),
            created_date=get_str_from_today(),
        )
        return FailureReceiveDataPresenter().transform(
            FailureReceiveDataUseCase().execute(dto=dto)
        )
