/*-
 * ~~~~~~licensing~~~~~~
 * artifact-management-extensions
 * ==========
 * 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.ext.binary;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.entaxy.platform.core.artifact.DefaultArtifact;

/**
 * Allowed content types: InputStream, File, byte[]
 */
public abstract class AbstractBinaryArtifact extends DefaultArtifact {

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

    @Override
    public void setContent(Object content) {
        super.setContent(content);
    }

    @Override
    public void toFile(File destination) {
        if (content == null)
            return;

        if (content instanceof File) {
            try {
                Files.copy(((File) content).getAbsoluteFile().toPath(), destination.getAbsoluteFile().toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                LOG.error("Error saving file", e);
            }
            return;
        }

        if (content instanceof InputStream) {
            try {
                InputStream is = (InputStream) content;
                if (is.markSupported()) {
                    is.mark(0);
                }
                Files.copy((InputStream) content, destination.getAbsoluteFile().toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
                if (is.markSupported()) {
                    is.reset();
                }
            } catch (IOException e) {
                LOG.error("Error saving file", e);
            }
            return;
        }

        if (content instanceof byte[]) {
            try (InputStream is = new ByteArrayInputStream((byte[]) content)) {
                Files.copy(is, destination.getAbsoluteFile().toPath(),
                        StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                LOG.error("Error saving file", e);
            }
            return;
        }

        super.toFile(destination);
    }

    @Override
    public byte[] asByteArray() {
        if (content == null)
            return new byte[0];

        if (content instanceof byte[])
            return (byte[]) content;

        if (content instanceof InputStream)
            try {
                byte[] byteArray;
                InputStream is = (InputStream) content;
                if (is.markSupported()) {
                    is.mark(0);
                }
                byteArray = IOUtils.toByteArray(is);
                if (is.markSupported()) {
                    is.reset();
                }
                return byteArray;
            } catch (IOException e) {
                LOG.error("Error getting bytes", e);
                return new byte[0];
            }

        if (content instanceof File)
            try (InputStream is = new FileInputStream((File) content)) {
                return IOUtils.toByteArray(is);
            } catch (Exception e) {
                LOG.error("Error getting bytes", e);
                return new byte[0];
            }

        return super.asByteArray();
    }

}
