package cn.reghao.bnt.web.devops.build.service.impl;

import cn.reghao.bnt.common.docker.DockerImpl;
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.result.Result;
import cn.reghao.jutil.jdk.web.result.ResultStatus;
import org.springframework.stereotype.Service;

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

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

    @Override
    public void addOrUpdate(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);
    }

    @Override
    public Result delete(int id) {
        dockerAuthRepository.deleteById(id);
        return Result.result(ResultStatus.SUCCESS);
    }
}
