package com.its.vms.api.controller;

import com.its.vms.api.dto.VmsControlDto;
import com.its.vms.api.service.VmsControlService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.NoSuchElementException;

@Slf4j
@Api(tags = "1.VMS-0.제어")
@Validated
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/vms/control")
public class VmsControlController {

    private final VmsControlService service;

    @ApiOperation(value = "VMS 제어기 리셋", response = VmsControlDto.VmsControlRes.class)
    @PostMapping(value = "/reset/{ctlrNmbr}", produces = {"application/json; charset=utf8"})
    public VmsControlDto.VmsControlRes controlReset(
            @ApiParam(name = "ctlrNmbr", value = "제어기번호", example = "10021", required = true)
            @PathVariable("ctlrNmbr") Long ctlrNmbr,
            @ApiParam(name = "req", value = "VMS 제어기 제어 정보", example = "[ADMIN]", required = true)
            @RequestBody @Valid final VmsControlDto.VmsControlReq req,
            HttpServletRequest request) {
        return this.service.controlReset(ctlrNmbr, req);
    }
    @ApiOperation(value = "VMS 제어기 리셋(CS)", response = VmsControlDto.VmsControlRes.class)
    @PostMapping(value = "/cs/reset/{key}/{ctlrNmbr}", produces = {"application/json; charset=utf8"})
    public VmsControlDto.VmsControlRes controlReset(
            @PathVariable final String key,
            @ApiParam(name = "ctlrNmbr", value = "제어기번호", example = "10021", required = true)
            @PathVariable("ctlrNmbr") Long ctlrNmbr,
            @ApiParam(name = "req", value = "VMS 제어기 제어 정보", example = "[ADMIN]", required = true)
            @RequestBody @Valid final VmsControlDto.VmsControlReq req) throws NoSuchElementException {
        log.warn("Vms reset: {}, {}, {}", key, ctlrNmbr, req);
        if (!StringUtils.equals(key, "abcdefg1234567890x")) {
            throw new NoSuchElementException("Authentication key mismatched: " + ctlrNmbr);
        }
        return this.service.controlReset(ctlrNmbr, req);
    }

}
