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

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.camel.tooling.model.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.base.support.osgi.bundle.CapabilityDescriptor;
import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport;
import ru.entaxy.platform.core.artifact.impl.CapabilityDescriptorImpl;

public class DefaultArtifact implements Artifact {

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

    protected ArtifactCoordinates coordinates;

    protected ArtifactSupport artifactSupport = null;

    protected Object content = null;

    protected String category = Artifact.ARTIFACT_CATEGORY_UNKNOWN;

    protected Map<String, Object> properties = new HashMap<>();

    protected List<Class<?>> supportedContentClasses = new ArrayList<>();

    protected Map<String, CapabilityDescriptorImpl> requiredCapabilities = new HashMap<>();
    protected Map<String, CapabilityDescriptorImpl> providedCapabilities = new HashMap<>();

    public DefaultArtifact() {
        this.coordinates = new ArtifactCoordinates();
        this.artifactSupport = this.getClass().getAnnotation(ArtifactSupport.class);
        initArtifact();
    }

    protected void initArtifact() {
        if (artifactSupport != null) {
            this.coordinates.type(artifactSupport.defaultArtifactType());
            this.coordinates.classifier(artifactSupport.defaultArtifactClassifier());
            this.setCategory(artifactSupport.supportedCategory());
            if (this.artifactSupport.supportedContentClasses() != null)
                for (int i = 0; i < this.artifactSupport.supportedContentClasses().length; i++)
                    this.supportedContentClasses.add(this.artifactSupport.supportedContentClasses()[i]);
        }
    }

    @Override
    public ArtifactCoordinates getCoordinates() {
        return coordinates;
    }

    public Object getContent() {
        return content;
    }

    public void setContent(Object content) {
        if (content == null)
            setNullContent();
        else {
            if (artifactSupport != null) {
                checkSetContent(content);
            } else
                this.content = content;
        }
    }

    protected void setNullContent() {
        this.content = null;
    }

    protected void checkSetContent(Object content) {
        // TODO throw exception if content suites none of the supported classes

        if (this.supportedContentClasses.contains(content.getClass())) {
            this.content = content;
        } else {
            for (Class<?> clazz : this.supportedContentClasses) {
                if (clazz.isInstance(content)) {
                    this.content = content;
                    return;
                }

            }
        }
    }

    @Override
    public String getCategory() {
        return this.category;
    }

    public void setCategory(String category) {
        if (!Strings.isNullOrEmpty(category))
            this.category = category;
        else
            this.category = Artifact.ARTIFACT_CATEGORY_UNKNOWN;
    }

    @Override
    public void toFile(File destination) {
        if (this.content != null) {
            try (FileWriter writer = new FileWriter(destination)) {
                writer.write(this.content.toString());
            } catch (IOException e) {
                log.error("Error writing to file", e);
            }
        }
    }

    @Override
    public byte[] asByteArray() {
        return null;
    }

    @Override
    public Map<String, Object> getProperties() {
        return properties;
    }

    @Override
    public CapabilityDescriptor provideCapability(String namespace) {
        if (!this.providedCapabilities.containsKey(namespace))
            this.providedCapabilities.put(namespace, new CapabilityDescriptorImpl(namespace));
        return this.providedCapabilities.get(namespace);
    }

    @Override
    public CapabilityDescriptor requireCapability(String namespace) {
        if (!this.requiredCapabilities.containsKey(namespace))
            this.requiredCapabilities.put(namespace, new CapabilityDescriptorImpl(namespace));
        return this.requiredCapabilities.get(namespace);
    }

    protected String getRequiredCapabilitiesValue() {
        return getCapabilitiesValue(requiredCapabilities);
    }

    protected String getProvidedCapabilitiesValue() {
        return getCapabilitiesValue(providedCapabilities);
    }

    protected String getCapabilitiesValue(Map<String, CapabilityDescriptorImpl> data) {
        String result = "";
        for (Map.Entry<String, CapabilityDescriptorImpl> entry : data.entrySet()) {
            if (!result.isEmpty())
                result += ",";
            result += entry.getKey();
            String attributes = entry.getValue().getAttributesAsString();
            if (!attributes.isEmpty())
                result += ";" + attributes;
        }
        return result;
    }
}
