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

import cn.reghao.autodop.common.msg.rpc.dto.app.PackType;
import cn.reghao.autodop.dmaster.app.db.query.config.PackerConfigQuery;
import cn.reghao.autodop.dmaster.app.model.po.config.build.PackerConfig;
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/packer")
public class PackerPageController {
    private PackerConfigQuery packerConfigQuery;

    public PackerPageController(PackerConfigQuery packerConfigQuery) {
        this.packerConfigQuery = packerConfigQuery;
    }

    @ApiOperation(value = "打包配置页面")
    @GetMapping
    public String packerPage(Model model) {
        PageRequest pageRequest = PageSort.pageRequest();
        Page<PackerConfig> page = packerConfigQuery.findAll(pageRequest);
        PageList<PackerConfig> pageList = PageList.pageList(page);

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

    @GetMapping("/add")
    public String addPackerPage(Model model) {
        setPackerModel(model);
        return "/app/config/packer/add";
    }

    @GetMapping("/edit/{id}")
    public String editPackerPage(@PathVariable("id") PackerConfig packerConfig, Model model) {
        setPackerModel(model);
        model.addAttribute("packer", packerConfig);
        return "/app/config/packer/add";
    }

    private void setPackerModel(Model model) {
        List<KeyValue> packTypes = new ArrayList<>();
        for (PackType packType : PackType.values()) {
            packTypes.add(new KeyValue(packType.name(), packType.name()));
        }
        model.addAttribute("packTypes", packTypes);
        model.addAttribute("machineId", MachineId.id());
        model.addAttribute("machineIpv4", MachineId.ipv4());
    }

    @GetMapping("/detail/{id}")
    public String packerDetailPage(@PathVariable("id") PackerConfig packerConfig, Model model) {
        model.addAttribute("packer", packerConfig);
        return "/app/config/packer/detail";
    }
}
