package cn.reghao.devops.web.mgr.builds.controller.page;

import cn.reghao.devops.web.mgr.builds.db.repository.CompilerConfigRepository;
import cn.reghao.devops.web.mgr.builds.model.po.CompilerConfig;
import cn.reghao.devops.web.mgr.app.model.vo.KeyValue;
import cn.reghao.devops.web.mgr.build.model.constant.CompileType;
import cn.reghao.devops.web.util.PageSort;
import cn.reghao.devops.common.machine.Machine;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * @author reghao
 * @date 2021-09-17 10:31:15
 */
@Slf4j
@Api(tags = "应用编译配置页面")
@Controller
@RequestMapping("/build/compiler")
public class CompilerPageController {
    private final CompilerConfigRepository compilerConfigRepository;

    public CompilerPageController(CompilerConfigRepository compilerConfigRepository) {
        this.compilerConfigRepository = compilerConfigRepository;
    }

    @ApiOperation(value = "编译配置页面")
    @GetMapping
    public String compilerConfigPage(Model model) {
        PageRequest pageRequest = PageSort.pageRequest();
        Page<CompilerConfig> page = compilerConfigRepository.findAll(pageRequest);

        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/devops/build/compiler/index";
    }

    @GetMapping("/add")
    public String addCompilerPage(Model model) {
        setCompilerModel(model);
        return "/devops/build/compiler/add";
    }

    @GetMapping("/edit/{id}")
    public String editCompilerPage(@PathVariable("id") CompilerConfig compilerConfig, Model model) {
        model.addAttribute("compiler", compilerConfig);
        return "/devops/build/compiler/edit";
    }

    private void setCompilerModel(Model model) {
        List<KeyValue> compileTypes = new ArrayList<>();
        for (CompileType compileType : CompileType.values()) {
            compileTypes.add(new KeyValue(compileType.name(), compileType.name()));
        }
        model.addAttribute("compileTypes", compileTypes);
        model.addAttribute("machineId", Machine.ID);
        model.addAttribute("machineIpv4", Machine.IPV4);
    }

    @GetMapping("/detail/{id}")
    public String compilerDetailPage(@PathVariable("id") CompilerConfig compilerConfig, Model model) {
        model.addAttribute("compiler", compilerConfig);
        return "/devops/build/compiler/detail";
    }
}
