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

import cn.reghao.devops.web.mgr.app.model.dto.AppConfigDto;
import cn.reghao.devops.web.mgr.app.model.dto.AppConfigUpdateDto;
import cn.reghao.devops.web.mgr.app.model.dto.CopyAppDto;
import cn.reghao.devops.web.mgr.app.model.po.config.AppConfig;
import cn.reghao.devops.web.mgr.app.service.AppBuildService;
import cn.reghao.jutil.jdk.result.Result;
import cn.reghao.jutil.jdk.result.WebResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @author reghao
 * @date 2019-11-27 11:29:43
 */
@Slf4j
@Api(tags = "应用配置 CRUD 接口")
@RestController
@RequestMapping("/api/app/config/app")
public class AppConfigController {
    private final AppBuildService appBuildService;

    public AppConfigController(AppBuildService appBuildService) {
        this.appBuildService = appBuildService;
    }

    @ApiOperation(value = "添加应用配置")
    @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE)
    public String addAppConfig(@Validated AppConfigDto appConfigDto) {
        Result result = appBuildService.createAppBuild(appConfigDto);
        return WebResult.result(result);
    }

    // TODO 使用 @PathVariable 注解时会自动填充实体
    @ApiOperation(value = "复制应用配置")
    @PostMapping(value = "/copy", produces = MediaType.APPLICATION_JSON_VALUE)
    public String copyAppConfig(@Validated CopyAppDto copyAppDto) {
        Result result = appBuildService.createByCopy(copyAppDto);
        return WebResult.result(result);
    }

    @ApiOperation(value = "修改应用配置")
    @PostMapping(value = "/update", produces = MediaType.APPLICATION_JSON_VALUE)
    public String updateAppConfig(@Validated AppConfigUpdateDto appConfigUpdateDto) {
        Result result = appBuildService.updateAppConfig(appConfigUpdateDto);
        return WebResult.result(result);
    }

    @ApiOperation(value = "删除应用配置")
    @DeleteMapping(value = "/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteAppConfig(@PathVariable("id") AppConfig app) {
        String appId = app.getAppId();
        Result result = appBuildService.deleteAppBuild(appId);
        return WebResult.result(result);
    }

    @ApiOperation(value = "清空应用本地仓库")
    @DeleteMapping(value = "/repo/{id}", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteAppLocalRepo(@PathVariable("id") AppConfig app) {
        String appId = app.getAppId();
        Result result = appBuildService.clearLocalRepo(appId);
        return WebResult.result(result);
    }
}
