/*-
 * ~~~~~~licensing~~~~~~
 * application-impl
 * ==========
 * 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.integration.applications.impl.build;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.core.artifact.ArtifactCoordinates;

public class ConfigStorage extends AbstractStorage<ConfigDescriptor> {

    private static final Logger LOG = LoggerFactory.getLogger(ConfigStorage.class);

    final String dirName = "repository";

    protected ConfigStorage(File parentDir, File tempDir) {
        super(parentDir, tempDir);
    }

    @Override
    protected String getStorageDir() {
        return dirName;
    }

    @Override
    public void prepare() {
        for (ConfigDescriptor desc : descriptors)
            prepareDescriptor(desc);

    }

    @Override
    public void prepareDescriptor(ConfigDescriptor descriptor) {
        ArtifactCoordinates configCoordinates = ArtifactCoordinates.fromUrl(descriptor.mavenLocation);

        if (!CommonUtils.isValid(configCoordinates.getType()))
            configCoordinates.type("cfg");

        String fileName = configCoordinates.toAssetName();
        String repositoryPath = configCoordinates.toRepositoryPath();
        String subfolder =
                repositoryPath.substring(0, repositoryPath.length() - fileName.length());

        File targetDir = new File(
                Paths.get(rootDirectory.getAbsolutePath(),
                        subfolder).toAbsolutePath().toUri());
        targetDir.mkdirs();

        File targetFile = new File(Paths.get(targetDir.getAbsolutePath(), fileName).toAbsolutePath().toUri());

        URL sourceUrl;
        try {
            sourceUrl = Paths.get(System.getProperty("karaf.etc"), descriptor.pid + ".cfg").toAbsolutePath().toUri()
                    .toURL();
        } catch (MalformedURLException e) {
            LOG.error("Error creating URL for [" + descriptor.mavenLocation + "]", e);
            return;
        }

        try (
                InputStream is = sourceUrl.openStream();
                OutputStream os = new FileOutputStream(targetFile)) {

            os.write(is.readAllBytes());

            String targetLocation =
                    dirName.concat(targetFile.getAbsolutePath().replace(rootDirectory.getAbsolutePath(), ""))
                            .replace('\\', '/');

            descriptor.finalLocation = targetLocation;

            descriptor.finalMavenLocation = descriptor.mavenLocation;

        } catch (IOException e) {
            LOG.error("Error reading from URL [" + sourceUrl.toString() + "]", e);
            return;
        }
    }

    @Override
    public BuildResult build(ArtifactCoordinates applicationCoordinates) {
        return new BuildResult();
    }

}
