package cn.reghao.devops.web.mgr.builds.service;

import cn.reghao.devops.common.docker.DockerImpl;
import cn.reghao.devops.common.docker.po.DockerAuth;
import cn.reghao.devops.web.mgr.builds.db.repository.DockerRegistryRepository;
import cn.reghao.devops.web.mgr.builds.model.po.DockerRegistry;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2024-07-26 19:16:57
 */
@Service
public class DockerRegistryService {
    private final DockerRegistryRepository dockerAuthRepository;

    public DockerRegistryService(DockerRegistryRepository dockerAuthRepository) {
        this.dockerAuthRepository = dockerAuthRepository;
    }

    public void addOrModify(DockerAuth dockerAuth) {
        DockerImpl docker = new DockerImpl(dockerAuth);
        docker.auth();

        String registryUrl = dockerAuth.getRegistryUrl();
        DockerRegistry dockerRegistry = dockerAuthRepository.findByRegistryUrl(registryUrl);
        if (dockerRegistry == null) {
            dockerRegistry = new DockerRegistry(dockerAuth);
        } else {
            dockerRegistry.setUsername(dockerAuth.getUsername());
            dockerRegistry.setPassword(dockerAuth.getPassword());
        }

        dockerAuthRepository.save(dockerRegistry);
    }

    public void delete(Integer id) {
        dockerAuthRepository.deleteById(id);
    }
}
