package cn.skcks.docking.gb28181.wvp.api.gb28181;

import cn.skcks.docking.gb28181.annotation.web.JsonMapping;
import cn.skcks.docking.gb28181.annotation.web.methods.GetJson;
import cn.skcks.docking.gb28181.annotation.web.methods.PostJson;
import cn.skcks.docking.gb28181.common.json.JsonResponse;
import cn.skcks.docking.gb28181.service.record.vo.RecordInfoItemVO;
import cn.skcks.docking.gb28181.wvp.config.SwaggerConfig;
import cn.skcks.docking.gb28181.wvp.service.catalog.CatalogService;
import cn.skcks.docking.gb28181.wvp.service.device.control.DeviceControlService;
import cn.skcks.docking.gb28181.wvp.service.record.RecordInfoService;
import cn.skcks.docking.gb28181.wvp.service.record.dto.RecordInfoDTO;
import cn.skcks.docking.gb28181.wvp.sip.message.message.catalog.dto.CatalogItemDTO;
import cn.skcks.docking.gb28181.wvp.sip.message.message.catalog.dto.CatalogResponseDTO;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.List;
import java.util.concurrent.CompletableFuture;

@RequiredArgsConstructor
@RestController
@JsonMapping("/gb28181")
public class Gb28181Controller {
    private final CatalogService catalogService;
    private final DeviceControlService deviceControlService;
    private final RecordInfoService recordInfoService;

    @Bean
    public GroupedOpenApi gb28181Api() {
        return SwaggerConfig.api("Gb28181Api", "/gb28181");
    }

    @SneakyThrows
    @GetJson("/catalog")
    public DeferredResult<JsonResponse<List<CatalogItemDTO>>> catalog(@RequestParam("gbDeviceId") String id){
        DeferredResult<JsonResponse<List<CatalogItemDTO>>> result = new DeferredResult<>();
        CompletableFuture<CatalogResponseDTO> catalog = catalogService.getCatalog(id);
        catalog.thenApplyAsync((dto)->{
            List<CatalogItemDTO> deviceList = dto.getDeviceList().getDeviceList();
            result.setResult(JsonResponse.success(deviceList));
            return null;
        });
        return result;
    }

    @SneakyThrows
    @GetJson("/deviceControl/recordCmd")
    public JsonResponse<Void> recordCmd(@RequestParam String deviceCode,@RequestParam String cmd){
        deviceControlService.sendRecordControl(deviceCode, cmd);
        return JsonResponse.success(null);
    }

    @PostJson("/recordInfo")
    public DeferredResult<JsonResponse<List<RecordInfoItemVO>>> recordInfo(RecordInfoDTO dto){
        return recordInfoService.requestRecordInfo(dto);
    }
}
