package cn.reghao.devops.web.mgr.machine.controller;

import cn.reghao.devops.web.mgr.machine.db.query.MachineQuery;
import cn.reghao.devops.web.mgr.machine.service.MachineService;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.devops.web.mgr.machine.model.po.SshAuth;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author reghao
 * @date 2019-08-30 18:49:15
 */
@Slf4j
@Api(tags = "机器接口")
@RestController
@RequestMapping("/api/machine/host")
public class MachineHostController {
    private final MachineService machineService;
    private final MachineQuery machineQuery;

    public MachineHostController(MachineService machineService, MachineQuery machineQuery) {
        this.machineService = machineService;
        this.machineQuery = machineQuery;
    }

    @ApiOperation(value = "设置机器环境")
    @PostMapping(value = "/env/{machineId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> editExtraMachineInfo(@PathVariable("machineId") String machineId,
                                                       @RequestParam("env") String env) {
        machineService.setEnv(machineId, env);
        return ResponseEntity.ok().body(WebResult.success());
    }

    @ApiOperation(value = "编辑 SSH 认证信息")
    @PostMapping(value = "/sshauth/{machineId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<String> editSshAuth(@PathVariable("machineId") String machineId, @Valid SshAuth sshAuth) {
        machineService.setSshAuth(machineId, sshAuth);
        return ResponseEntity.ok().body(WebResult.success());
    }

    @ApiOperation(value = "删除机器")
    @DeleteMapping(value = "/{machineId}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String machine(@PathVariable("machineId") String machineId) {
        if (machineQuery.isAgentOnline(machineId)) {
            return WebResult.failWithMsg("机器处于在线状态, 不能删除");
        }

        Result result = machineService.delete(machineId);
        return WebResult.result(result);
    }

    @PostMapping(value = "/deprecate", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteAll(@RequestParam(value = "ids") List<String> machineIds) {
        Result result = machineService.updateMachineStat(machineIds);
        return WebResult.result(result);
    }
}
