/*-
 * ~~~~~~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.repository.impl;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.camel.tooling.model.Strings;
import org.apache.karaf.cave.repository.Repository;
import org.apache.karaf.cave.repository.RepositoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import ru.entaxy.platform.base.support.xml.CommonXMLUtils;
import ru.entaxy.platform.core.artifact.Artifact;
import ru.entaxy.platform.core.artifact.ArtifactCoordinates;
import ru.entaxy.platform.core.artifact.DeployedArtifact;
import ru.entaxy.platform.core.artifact.repository.ArtifactRepository;
import ru.entaxy.platform.core.artifact.repository.RepositoryDescriptor;
import ru.entaxy.platform.core.artifact.repository.impl.remote.RemoteRepository;
import ru.entaxy.platform.core.artifact.repository.impl.remote.RemoteRepositoryDescriptor;
import ru.entaxy.platform.core.artifact.repository.impl.remote.RemoteRepositoryFactory;

public class ArtifactRepositoryImpl implements ArtifactRepository {

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

    protected boolean isHealthy = false;

    protected RepositoryService repositoryService;

    protected RepositoryDescriptor repositoryDescriptor;

    protected RemoteRepository remoteRepository = null;

    public ArtifactRepositoryImpl() {
        // TODO Auto-generated constructor stub
    }

    public ArtifactRepositoryImpl(RepositoryDescriptor descriptor) {
        this();
        this.repositoryDescriptor = descriptor;
    }

    public void init() {
        Repository caveRepo = repositoryService.repository(repositoryDescriptor.getName());
        if (caveRepo == null) {
            caveRepo = createRepo();
        } else {
            caveRepo = checkUpdateRepo(caveRepo);
        }
    }

    protected Repository createRepo() {
        Repository repo = null;
        try {
            repo = repositoryService.create(
                    repositoryDescriptor.getName(),
                    repositoryDescriptor.getLocation(),
                    Strings.isNullOrEmpty(repositoryDescriptor.getUrl())
                            ? "/repositories/" + repositoryDescriptor.getName()
                            : repositoryDescriptor.getUrl(),
                    repositoryDescriptor.isProxy() && !Strings.isNullOrEmpty(repositoryDescriptor.getRemotes())
                            ? repositoryDescriptor.getRemotes()
                            : null,
                    /*
                    repositoryDescriptor.isProxy() && !Strings.isNullOrEmpty(repositoryDescriptor.getRemotes())
                    		&& !Strings.isNullOrEmpty(repositoryDescriptor.getLocation())
                    	?repositoryDescriptor.isMirror()
                    	:false*/
                    repositoryDescriptor.isMirror(),
                    "karaf",
                    null,
                    null,
                    null,
                    null,
                    8);
            this.isHealthy = true;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("createRepo", e);
            this.isHealthy = false;
        }
        return repo;
    }

    protected Repository checkUpdateRepo(Repository repo) {
        try {
            log.info("repositoryDescriptor.getLocation(): [{}]; repo.getLocation(): [{}]",
                    repositoryDescriptor.getLocation(), repo.getLocation());
            if (!Strings.isNullOrEmpty(repositoryDescriptor.getLocation())
                    && !repo.getLocation().equalsIgnoreCase(repositoryDescriptor.getLocation()))
                repositoryService.changeLocation(repositoryDescriptor.getName(), repositoryDescriptor.getLocation());
            if (!repo.getUrl().equalsIgnoreCase(repositoryDescriptor.getUrl())
                    && !Strings.isNullOrEmpty(repositoryDescriptor.getUrl()))
                repositoryService.changeUrl(repositoryDescriptor.getName(), repositoryDescriptor.getUrl());
            String repoProxy = repo.getProxy();
            boolean repoIsProxy = !Strings.isNullOrEmpty(repoProxy);
            if (repoIsProxy != repositoryDescriptor.isProxy()) {
                if (!repositoryDescriptor.isProxy())
                    repositoryService.changeProxy(repositoryDescriptor.getName(), "", false);
                else
                    repositoryService.changeProxy(repositoryDescriptor.getName(), repositoryDescriptor.getRemotes(),
                            repositoryDescriptor.isMirror());
            }
            this.isHealthy = true;
        } catch (Exception e) {
            log.error("checkUpdateRepo", e);
            this.isHealthy = false;
        }
        return repo;
    }

    @Override
    public DeployedArtifact deploy(Artifact artifact) throws Exception {
        if (isHealthy() && isEnabled() && !isReadOnly()) {
            return deployArtifact(artifact);
        }
        return new DeployedArtifactImpl(artifact);
    }

    protected DeployedArtifact deployArtifact(Artifact artifact) throws Exception {
        String location = "mvn:";

        if (!repositoryDescriptor.isProxy() || repositoryDescriptor.isMirror())
            deployToCave(artifact);

        if (repositoryDescriptor.isProxy())
            deployToRemoteMaven(artifact);

        return new DeployedArtifactImpl(artifact, location + artifact.getCoordinates().toString());
    }

    protected void deployToCave(Artifact artifact) {
        if (artifact.getContent() != null) {
            try {
                ArtifactCoordinates coords = artifact.getCoordinates();
                File tmpFile = File.createTempFile(getName() + "-", Calendar.getInstance().getTimeInMillis() + "");
                artifact.toFile(tmpFile);
                log.info("Artifact [{}] is written to [{}]", artifact.getCoordinates(),
                        tmpFile.toURI().toURL().toString());
                repositoryService.addArtifact(tmpFile.toURI().toURL().toString(), coords.getGroupId(),
                        coords.getArtifactId(), coords.getVersion(), coords.getType(), coords.getClassifier(),
                        getName());
                log.info("Artifact [{}] is deployed to [{}]", artifact.getCoordinates(), getName());
                // Files.deleteIfExists(tmpFil)
            } catch (IOException e) {
                log.error("deployToCave", e);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                log.error("deployToCave", e);
            }
        }
    }

    protected void deployToRemoteMaven(Artifact artifact) throws Exception {
        try {
            initRemoteRepository();
            this.remoteRepository.deploy(artifact);
        } catch (Exception e) {
            log.error("deployToRemoteMaven", e);
            throw e;
        }
    }

    protected void initRemoteRepository() throws NoSuchMethodException, SecurityException, InstantiationException,
            IllegalAccessException, IllegalArgumentException, InvocationTargetException, MalformedURLException {
        if (this.remoteRepository == null) {
            this.remoteRepository =
                    RemoteRepositoryFactory.create(new RemoteRepositoryDescriptor(repositoryDescriptor));
        }
    }

    @Override
    public String getName() {
        return repositoryDescriptor.getName();
    }

    @Override
    public boolean isHealthy() {
        return this.isHealthy;
    }

    @Override
    public boolean isEnabled() {
        return repositoryDescriptor.isEnabled();
    }

    @Override
    public boolean isReadOnly() {
        return repositoryDescriptor.isReadOnly();
    }

    @Override
    public boolean isSnapshotsAllowed() {
        return repositoryDescriptor.isSnapshots();
    }

    @Override
    public String getUrl() {
        return repositoryService.repository(getName()).getUrl();
    }

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

    @Override
    public boolean isSystem() {
        return this.repositoryDescriptor.isSystem();
    }

    @Override
    public List<String> getAvailableVersions(Artifact artifact) {

        File f = new File(repositoryService.repository(getName()).getLocation());
        if (!f.exists())
            return null;
        Path target = Paths.get(
                f.getAbsoluteFile().toPath().toString(),
                artifact.getCoordinates().getGroupId().replace('.', File.separatorChar),
                artifact.getCoordinates().getArtifactId(),
                "maven-metadata-local.xml");
        File metadata = target.toFile();
        if (!metadata.exists())
            return null;
        try {
            Document xml = CommonXMLUtils.getDocument(target.toUri().toURL());
            NodeList nodes = xml.getElementsByTagName("version");
            List<String> result = new ArrayList<>();

            for (int i = 0; i < nodes.getLength(); i++) {
                result.add(nodes.item(i).getTextContent());
            }

            return result;
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            log.error("getAvailableVersions", e);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            log.error("getAvailableVersions", e);
        }
        return null;
    }
}
