/*-
 * ~~~~~~licensing~~~~~~
 * artifact-management
 * ==========
 * Copyright (C) 2020 - 2025 EmDev LLC
 * ==========
 * You may not use this file except in accordance with the License Terms of the Copyright
 * Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
 * rights to the Software and any copies are the property of the Copyright Holder. Unless
 * it is explicitly allowed the Copyright Holder, the User is prohibited from using the
 * Software for commercial purposes to provide services to third parties.
 * 
 * The Copyright Holder hereby declares that the Software is provided on an "AS IS".
 * Under no circumstances does the Copyright Holder guarantee or promise that the
 * Software provided by him will be suitable or not suitable for the specific purposes
 * of the User, that the Software will meet all commercial and personal subjective
 * expectations of the User, that the Software will work properly, without technical
 * errors, quickly and uninterruptedly.
 * 
 * Under no circumstances shall the Copyright Holder or its Affiliates is not liable
 * to the User for any direct or indirect losses of the User, his expenses or actual
 * damage, including, downtime; loss of bussines; lost profit; lost earnings; loss
 * or damage to data, property, etc.
 * ~~~~~~/licensing~~~~~~
 */
package ru.entaxy.platform.core.artifact.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.karaf.cave.repository.RepositoryService;
import org.osgi.framework.BundleContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.artifact.Artifact;
import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.installer.builder.InstallersWithDefaults;
import ru.entaxy.platform.core.artifact.installer.builder.impl.InstallersWithDefaultsImpl;
import ru.entaxy.platform.core.artifact.repository.ArtifactRepository;
import ru.entaxy.platform.core.artifact.repository.RepositoryDescriptor;
import ru.entaxy.platform.core.artifact.repository.RepositoryDescriptorCollector;
import ru.entaxy.platform.core.artifact.repository.impl.ArtifactRepositoryImpl;
import ru.entaxy.platform.core.artifact.repository.impl.DeployedArtifactImpl;
import ru.entaxy.platform.core.artifact.repository.impl.RepositoryRegistrator;
import ru.entaxy.platform.core.artifact.service.ArtifactService;

public class ArtifactServiceImpl implements ArtifactService, RepositoryDescriptorCollector {

    protected Map<String, ArtifactRepository> repositories = new HashMap<>();

    protected BundleContext bundleContext;

    protected RepositoryService repositoryService;

    protected InstallersWithDefaultsImpl installers;

    private boolean httpEnabled;

    private final static Logger log = LoggerFactory.getLogger(ArtifactServiceImpl.class);

    public ArtifactServiceImpl() {
        installers = new InstallersWithDefaultsImpl();
    }

    public void addRepository(ArtifactRepository repository) {

    }

    @Override
    public void addRepositoryDescriptor(RepositoryDescriptor helper) {
        log.info("Added descriptor for repository [{}]", helper.getName());
        if (!repositories.containsKey(helper.getName())) {
            ArtifactRepository repo = createRepository(helper);
            this.repositories.put(repo.getName(), repo);
            if (helper.isLookupEnabled())
                RepositoryRegistrator.INSTANCE.addRepository(repo, httpEnabled);
        }
    }

    @Override
    public void removeRepositoryDescriptor(RepositoryDescriptor helper) {
        // FIX for first start
        if (repositories != null && helper != null) {
            if (helper.isLookupEnabled())
                RepositoryRegistrator.INSTANCE.removeRepository(repositories.get(helper.getName()));
            repositories.remove(helper.getName());
        }
    }

    protected ArtifactRepository createRepository(RepositoryDescriptor helper) {
        ArtifactRepositoryImpl repo = new ArtifactRepositoryImpl(helper);
        synchronized (repositories) {
            repositories.put(repo.getName(), repo);
        }
        repo.setRepositoryService(repositoryService);
        repo.init();
        return repo;
    }

    @Override
    public DeployedArtifact deployLocal(Artifact artifact) {
        return deploy(artifact, ArtifactRepository.REPO_NAME_LOCAL);
    }

    @Override
    public DeployedArtifact deployShared(Artifact artifact) {
        return deploy(artifact, ArtifactRepository.REPO_NAME_SHARED);
    }

    protected DeployedArtifact deploy(Artifact artifact, String repositoryName) {
        String error = "Repository [" + repositoryName + "] not found";
        if (repositories.containsKey(repositoryName)) {
            ArtifactRepository repo = repositories.get(repositoryName);
            error = String.format("Cannot deploy artifact [%s] to repository [" + repositoryName + "]",
                    artifact.getCoordinates().toString());
            if (repo.isHealthy())
                if (repo.isEnabled())
                    if (!repo.isReadOnly()) {
                        try {
                            return repo.deploy(artifact);
                        } catch (Exception e) {
                            error += ": ".concat(e.getMessage());
                        }
                    }
                    else
                        error += ": repository is readonly";
                else
                    error += ": repository is disabled";
            else
                error += ": repository is not healthy";
        }
        log.error(error);
        return new DeployedArtifactImpl(artifact);
    }

    @Override
    public ArtifactRepository getRepository(String name) {
        return this.repositories.get(name);
    }

    @Override
    public List<ArtifactRepository> getRepositories() {
        return new ArrayList<>(this.repositories.values());
    }

    public void setBundleContext(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
    }

    public void setRepositoryService(RepositoryService repositoryService) {
        this.repositoryService = repositoryService;
    }

    @Override
    public InstallersWithDefaults installers() {
        return this.installers;
    }

    public void setInstallers(InstallersWithDefaultsImpl installers) {
        this.installers = installers;
    }

    public void setHttpEnabled(boolean httpEnabled) {
        this.httpEnabled = httpEnabled;
    }

}
