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

import cn.reghao.bnt.common.docker.model.DockerAuth;
import cn.reghao.bnt.web.devops.build.db.repository.DockerRegistryRepository;
import cn.reghao.bnt.web.devops.build.model.po.DockerRegistry;
import cn.reghao.bnt.web.devops.build.service.DockerRegistryService;
import cn.reghao.jutil.jdk.web.db.PageList;
import cn.reghao.jutil.web.WebResult;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author reghao
 * @date 2024-07-26 17:36:37
 */
@Tag(name = "DockerRegistry 配置页面")
@RestController
@RequestMapping("/api/devops/build/registry")
public class DockerRegistryController {
    private final DockerRegistryRepository dockerRegistryRepository;
    private final DockerRegistryService dockerRegistryService;
    private final int pageSize = 10;

    public DockerRegistryController(DockerRegistryRepository dockerRegistryRepository,
                                    DockerRegistryService dockerRegistryService) {
        this.dockerRegistryRepository = dockerRegistryRepository;
        this.dockerRegistryService = dockerRegistryService;
    }

    @Operation(summary = "DockerRegistry 列表页面", description = "N")
    @GetMapping("")
    public String repoAuthPage(@RequestParam("pn") int pageNumber) {
        PageRequest pageRequest = PageRequest.of(pageNumber-1, pageSize);
        Page<DockerRegistry> page = dockerRegistryRepository.findAll(pageRequest);
        PageList<DockerRegistry> pageList = getPageList(page);
        return WebResult.success(pageList);
    }

    private PageList<DockerRegistry> getPageList(Page<DockerRegistry> page) {
        int pageNumber = page.getNumber() + 1;
        int pageSize = page.getSize();
        long total = page.getTotalElements();
        List<DockerRegistry> list = page.getContent();
        return PageList.pageList(pageNumber, pageSize, (int) total, list);
    }

    @Operation(summary = "添加 DockerRegistry 配置", description = "N")
    @PostMapping(value = "", produces = MediaType.APPLICATION_JSON_VALUE)
    public String addOrUpdateRepoConfig(@Validated DockerAuth dockerAuth) {
        dockerRegistryService.addOrUpdate(dockerAuth);
        return WebResult.success();
    }

    @Operation(summary = "删除 DockerRegistry 配置", description = "N")
    @PostMapping(value = "/delete", produces = MediaType.APPLICATION_JSON_VALUE)
    public String deleteRepoConfig(Integer id) {
        dockerRegistryService.delete(id);
        return WebResult.success();
    }
}
