/*-
 * ~~~~~~licensing~~~~~~
 * resource-based-storage
 * ==========
 * 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.storage.resource.impl.project;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Map;

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

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceURLFactory;
import ru.entaxy.platform.integration.applications.ApplicationProjectItem;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProject;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion;
import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor;
import ru.entaxy.platform.integration.applications.exceptions.ItemException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionIsDirtyException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionNotConsistentException;
import ru.entaxy.platform.integration.applications.impl.build.ApplicationBuilder;
import ru.entaxy.platform.integration.applications.impl.project.ApplicationProjectContentImpl;
import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponent;
import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObject;
import ru.entaxy.platform.objects.runtime.EntaxyRuntimeObjectResource;

public class ProjectVersionComponent extends AbstractResourceComponent<ProjectVersionData>
        implements EntaxyApplicationProjectVersion {

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

    String versionNumber;

    ProjectComponent applicationComponent;

    ApplicationProjectContentImpl applicationContent = new ApplicationProjectContentImpl();

    EntaxyResource contentResource;

    BuildComponent buildComponent;

    final String CONTENT_RESOURCE_NAME = "version.content";

    VERSION_STATUS status = VERSION_STATUS.NEW;

    private boolean isDirty = false;

    protected void setDirty(boolean isDirty) {
        this.isDirty = isDirty;
    }

    /*
    public ProjectVersionComponent(EntaxyResourceService entaxyResourceService, ProjectComponent applicationComponent,
            String versionNumber) {
        super(entaxyResourceService);
        this.versionNumber = versionNumber;
        this.applicationComponent = applicationComponent;
        this.rootResourceFolderUrl =
                applicationComponent.getRootResourceFolderUrl().concat("/").concat(this.versionNumber);
        applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName());
        applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber);
    
        buildComponent = new BuildComponent(entaxyResourceService, rootResourceFolderUrl);
    }
    */

    public ProjectVersionComponent(ResourceContext parentResourceContext, ProjectComponent applicationComponent,
            String versionNumber) {
        super(parentResourceContext.subcontext(versionNumber));
        this.versionNumber = versionNumber;
        this.applicationComponent = applicationComponent;
        applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName());
        applicationContent.getProperties().put(STANDARD_PROPERTIES.GROUP, applicationComponent.getGroup());
        applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber);

        buildComponent = new BuildComponent(resourceContext);
    }

    @Override
    protected Class<ProjectVersionData> getDataObjectClass() {
        return ProjectVersionData.class;
    }

    @Override
    protected String getRootResourceName() {
        return ".version";
    }

    @Override
    protected ProjectVersionData createDataObject() {
        return new ProjectVersionData(this.versionNumber, this.status.toString());
    }

    @Override
    public String getComponentKey() {
        return versionNumber;
    }

    @Override
    protected void initializeDataObject() throws Exception {
        // TODO Auto-generated method stub
        super.initializeDataObject();
        this.status = VERSION_STATUS.valueOf(dataObject.status);
    }

    @Override
    public void init() {
        super.init();
        initContent();
        buildComponent.init();
    }

    protected void initContent() {
        if (contentResource == null) {
            contentResource = getResource(CONTENT_RESOURCE_NAME);
            if (!contentResource.exists()) {
                save();
            } else {
                applicationContent.unmarshall(contentResource.getAsString());
            }
        }
    }

    public String getAsJsonString() {
        return applicationContent.marshall();
    }

    public void updateFromString(String jsonData) {
        applicationContent.unmarshall(jsonData);
        applicationContent.getProperties().put(STANDARD_PROPERTIES.APPLICATION, applicationComponent.getName());
        applicationContent.getProperties().put(STANDARD_PROPERTIES.GROUP, applicationComponent.getGroup());
        applicationContent.getProperties().put(STANDARD_PROPERTIES.VERSION, versionNumber);
    }

    /* EntaxyApplicationProjectVersion implementation */

    @Override
    public void disgard() {
        applicationContent.unmarshall(contentResource.getAsString());
    }

    @Override
    public void save() {
        String data = applicationContent.marshall();
        try (ByteArrayInputStream bis = new ByteArrayInputStream(data.getBytes())) {
            contentResource.save(bis);
            setDirty(false);
        } catch (IOException e) {
            LOG.error("Error saving resource [" + contentResource.getURL() + "]", e);
        }
    }

    @Override
    public String getVersionNumber() {
        return versionNumber;
    }

    @Override
    public List<ApplicationProjectItem> getItems() {
        return applicationContent.getItems();
    }

    @Override
    public <T extends ApplicationProjectItem> List<T> getItems(Class<T> itemClass) {
        return applicationContent.getItems(itemClass);
    }

    @Override
    public void addItem(ApplicationProjectItem item) throws ItemException {
        try {
            applicationContent.addItem(item);
            setDirty(true);
        } catch (ItemException e) {
            e.setVersionNumber(versionNumber);
            e.setApplicationName(this.applicationComponent.getName());
            throw e;
        }
    }

    @Override
    public void ignoreItem(ApplicationProjectItem item) throws ItemException {
        try {
            applicationContent.ignoreItem(item);
            setDirty(true);
        } catch (ItemException e) {
            e.setVersionNumber(versionNumber);
            e.setApplicationName(this.applicationComponent.getName());
            throw e;
        }
    }

    @Override
    public void removeItem(ApplicationProjectItem item) throws ItemException {
        try {
            applicationContent.removeItem(item);
            setDirty(true);
        } catch (ItemException e) {
            e.setVersionNumber(versionNumber);
            e.setApplicationName(this.applicationComponent.getName());
            throw e;
        }
    }

    @Override
    public EntaxyApplicationProject getApplication() {
        return this.applicationComponent;
    }

    @Override
    public ApplicationProjectItem addObject(EntaxyRuntimeObject runtimeObject) {
        setDirty(true);
        return applicationContent.addObject(runtimeObject);
    }

    @Override
    public ApplicationProjectItem addResource(EntaxyRuntimeObjectResource runtimeObjectResource) {
        setDirty(true);
        return applicationContent.addResource(runtimeObjectResource);
    }

    @Override
    public ApplicationProjectItem addResource(EntaxyResource entaxyResource) {
        setDirty(true);
        return applicationContent.addResource(entaxyResource);
    }

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

    @Override
    public VERSION_STATUS getStatus() {
        return status;
    }

    @Override
    public URL build() throws ProjectVersionException {
        if (!isConsistent())
            throw new ProjectVersionNotConsistentException(applicationComponent.getName(), versionNumber);
        if (isDirty())
            throw new ProjectVersionIsDirtyException(applicationComponent.getName(), versionNumber);
        ApplicationBuilder builder = new ApplicationBuilder(applicationContent);
        builder.getCoordinates()
                .groupId(applicationComponent.getGroup())
                .artifactId(applicationComponent.getName())
                .version(versionNumber);
        URL result = builder.build();
        buildComponent.updateBuild(result, builder.getDescriptor(), builder.getCoordinates());
        builder.clear();
        if (isBuildAvailable()) {
            status = VERSION_STATUS.BUILT;
            dataObject.status = status.toString();
            try {
                updateRootResource();
            } catch (Exception e) {
                LOG.error("Error updating root resource for project [" + applicationComponent.getName()
                        + "] version [" + versionNumber + "]", e);
            }
            try {
                return EntaxyResourceURLFactory.getGlobalUrl(buildComponent.getBuildResource());
            } catch (MalformedURLException e) {
                LOG.error("Error creating URL for [" + buildComponent.getBuildResource().getURL() + "]", e);
                return null;
            }
        }
        return null;
    }

    @Override
    public InputStream getBuild() {
        if (!isBuildAvailable())
            return null;
        return buildComponent.getBuildResource().getInputStream();
    }

    @Override
    public URL getBuildUrl() {
        if (!isBuildAvailable())
            return null;
        try {
            return EntaxyResourceURLFactory.getGlobalUrl(buildComponent.getBuildResource());
        } catch (MalformedURLException e) {
            LOG.error("Error getting global URL for resource [" + buildComponent.getBuildResource().getURL() + "]", e);
            return null;
        }
    }

    @Override
    public boolean isBuildAvailable() {
        return buildComponent.isBuildAvailable();
    }

    @Override
    public ApplicationDescriptor getBuildInfo() {
        return buildComponent.getApplicationDescriptor();
    }

    @Override
    public boolean isDirty() {
        return isDirty;
    }
}
