package cn.reghao.bnt.web.devops.build.controller;

import cn.reghao.bnt.web.devops.build.model.po.BuildDir;
import cn.reghao.bnt.web.devops.build.service.BuildDirService;
import cn.reghao.bnt.web.devops.util.DefaultSetting;
import cn.reghao.bnt.web.util.SelectOption;
import cn.reghao.jutil.jdk.web.result.Result;
import cn.reghao.jutil.web.WebResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author reghao
 * @date 2019-08-30 18:49:15
 */
@Slf4j
@Tag(name = "构建目录配置页面")
@RestController
@RequestMapping("/api/devops")
public class BuildDirController {
    private final BuildDirService buildDirService;
    private final DefaultSetting defaultSetting;

    public BuildDirController(BuildDirService buildDirService, DefaultSetting defaultSetting) {
        this.buildDirService = buildDirService;
        this.defaultSetting = defaultSetting;
    }

    @Operation(summary = "构建目录页面", description = "N")
    @GetMapping(value = "/build/dir", produces = MediaType.APPLICATION_JSON_VALUE)
    public String buildDirPage() {
        BuildDir buildDir = buildDirService.get();
        List<BuildDir> list = List.of(buildDir);
        return WebResult.success(list);
    }

    @Operation(summary = "清空构建目录", description = "N")
    @PostMapping(value = "/build/dir/erase", produces = MediaType.APPLICATION_JSON_VALUE)
    public String emptyBuildDir() {
        Result result = buildDirService.erase();
        return WebResult.result(result);
    }

    @Operation(summary = "环境和应用类型列表", description = "N")
    @GetMapping(value = "/envs", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getEnvList() {
        String userEnv = defaultSetting.getDefaultEnv();
        List<SelectOption> envList = defaultSetting.getEnvList().stream()
                .map(env -> new SelectOption(env, env))
                .collect(Collectors.toList());

        String userAppType = defaultSetting.getDefaultAppType();
        List<SelectOption> appTypeList = defaultSetting.getAppTypeList().stream()
                .map(env -> new SelectOption(env, env))
                .collect(Collectors.toList());

        Map<String, Object> map = new HashMap<>();
        map.put("userEnv", userEnv);
        map.put("envList", envList);
        map.put("userAppType", userAppType);
        map.put("appTypeList", appTypeList);
        return WebResult.success(map);
    }
}
