/*-
 * ~~~~~~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.nio.charset.StandardCharsets;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;

import ru.entaxy.platform.base.support.xml.CommonXMLUtils;
import ru.entaxy.platform.core.artifact.annotation.ArtifactSupport;

@ArtifactSupport(supportedCategory = Artifact.ARTIFACT_CATEGORY_BLUEPRINT,
        supportedContentClasses = {String.class, Document.class, byte[].class},
        defaultArtifactClassifier = Artifact.ARTIFACT_CATEGORY_BLUEPRINT, defaultArtifactType = "xml")
public class Blueprint extends DefaultArtifact implements Manifested {

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

    public static final String ARTIFACT_CATEGORY_BLUEPRINT = "blueprint";

    protected BlueprintManifest manifest = null;

    @Override
    public void setContent(Object content) {
        super.setContent(content);
        if (this.content.getClass().equals(byte[].class)) {
            String s = new String((byte[]) this.content, StandardCharsets.UTF_8);
            this.content = s;
        }
        if (this.content.getClass().equals(String.class)) {
            try {
                Document d = CommonXMLUtils.parseString(false, (String) this.content);
                this.content = d;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    @Override
    public ArtifactManifest getManifest() {
        if (this.manifest == null)
            this.manifest = new BlueprintManifest(this);
        if (this.content instanceof Document)
            this.manifest.load((Document) this.content);
        return this.manifest;
    }

    @Override
    public void toFile(File destination) {
        if (this.content instanceof String)
            super.toFile(destination);
        else if (this.content instanceof Document) {
            Document doc = (Document) this.content;
            try {
                asByteArray();
                CommonXMLUtils.saveDocument(doc, destination);
            } catch (Exception e) {
                log.error("Error saving to file", e);
            }
        } else if (this.content instanceof byte[]) {
            // TODO to be implemented
        }

    }

    @Override
    public byte[] asByteArray() {
        if (this.content instanceof byte[])
            return (byte[]) this.content;
        if (this.content instanceof String)
            return ((String) this.content).getBytes();
        if (this.content instanceof Document)
            try {
                Document doc = (Document) this.content;

                // make sure manifest exists
                getManifest();

                if (!this.manifest.isLoaded())
                    this.manifest.load(doc);
                this.manifest.save(doc);
                return CommonXMLUtils.doc2string(doc).getBytes();
            } catch (Exception e) {
                log.error("Error getting as byte[]: " + this.getCoordinates().toString(), e);
            }
        return new byte[] {};
    }

}
