package cn.reghao.autodop.dmaster.app.controller.page;

import cn.reghao.autodop.dmaster.app.db.query.config.CompilerConfigQuery;
import cn.reghao.autodop.dmaster.app.model.constant.build.CompileType;
import cn.reghao.autodop.dmaster.app.model.po.config.build.CompilerConfig;
import cn.reghao.autodop.dmaster.app.model.vo.KeyValue;
import cn.reghao.autodop.dmaster.util.db.PageList;
import cn.reghao.autodop.dmaster.util.db.PageSort;
import cn.reghao.jdkutil.machine.MachineId;
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("/app/config/build/compiler")
public class CompilerPageController {
    private final CompilerConfigQuery compilerConfigQuery;

    public CompilerPageController(CompilerConfigQuery compilerConfigQuery) {
        this.compilerConfigQuery = compilerConfigQuery;
    }

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

        model.addAttribute("page", page);
        model.addAttribute("list", pageList.getList());
        return "/app/config/compiler/index";
    }

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

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

    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", MachineId.id());
        model.addAttribute("machineIpv4", MachineId.ipv4());
    }

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