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

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion;
import ru.entaxy.platform.integration.applications.descriptor.ApplicationDescriptor;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationCausedException;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationException;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationImportCausedException;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionAlreadyExists;
import ru.entaxy.platform.integration.applications.exceptions.StorageException;
import ru.entaxy.platform.integration.applications.impl.ExportImportHelper.ApplicationImporter;
import ru.entaxy.platform.integration.applications.impl.StorageApplicationContentAdapter;
import ru.entaxy.platform.integration.applications.impl.StorageImportAdapter;
import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationComponent;
import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationVersionComponent;

public class ApplicationStorageComponent extends AbstractResourceComponent<ApplicationStorageData>
        implements StorageImportAdapter {

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

    final protected Map<String, ApplicationComponent> applicationCache = new HashMap<>();

    protected Object applicationCacheLock = new Object();

    /*
    public ApplicationStorageComponent(EntaxyResourceService entaxyResourceService, String parentRootUrl) {
        super(entaxyResourceService);
        this.rootResourceFolderUrl = parentRootUrl.concat("/").concat("applications");
    }
    */

    public ApplicationStorageComponent(ResourceContext parentResourceContext) {
        super(parentResourceContext.subcontext("applications"));
    }

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

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

    @Override
    protected ApplicationStorageData createDataObject() {
        return new ApplicationStorageData();
    }

    @Override
    public String getComponentKey() {
        return "applications";
    }

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

    protected void initializeApplicationCache() {
        synchronized (applicationCacheLock) {
            if (dataObject.applications == null)
                return;
            for (String applicationName : dataObject.applications) {
                ApplicationComponent comp = loadApplication(applicationName);
                if (comp != null)
                    applicationCache.put(comp.getName(), comp);
            }
        }
    }

    protected ApplicationComponent loadApplication(String applicationName) {
        try {
            ApplicationComponent component =
                    new ApplicationComponent(resourceContext, applicationName);
            component.init();
            return component;
        } catch (Exception e) {
            LOG.error("Error loading application [" + applicationName + "]", e);
        }
        return null;
    }

    public boolean applicationExists(String applicationName) {
        return dataObject.hasApplication(applicationName);
    }

    public List<ApplicationComponent> getApplications() {
        return new ArrayList<>(applicationCache.values());
    }

    public ApplicationComponent getApplication(String applicationName) {
        return applicationCache.get(applicationName);
    }

    protected ApplicationComponent getOrCreateApplication(String applicationName)
            throws ApplicationException, StorageException {
        ApplicationComponent result = getApplication(applicationName);
        if (result != null)
            return result;
        result = createApplication(applicationName);
        return result;
    }

    public void addApplication(EntaxyApplication application) throws ApplicationException, StorageException {
        // TODO Auto-generated method stub

    }

    public void removeApplication(EntaxyApplication application)
            throws ApplicationException, StorageException {
        synchronized (applicationCacheLock) {
            String applicationName = application.getName();
            ApplicationComponent comp = applicationCache.get(applicationName);
            if (comp == null)
                return;
            comp.delete();
            applicationCache.remove(applicationName);
            dataObject.removeApplication(applicationName);
            try {
                updateRootResource();
            } catch (Exception e) {
                LOG.error("Error removing application [" + applicationName + "]", e);
            }
        }
    }

    protected ApplicationComponent createApplication(String applicationName)
            throws ApplicationException, StorageException {
        try {
            ApplicationComponent component =
                    new ApplicationComponent(resourceContext, applicationName);
            component.init();
            synchronized (applicationCacheLock) {
                dataObject.addApplication(applicationName);
                updateRootResource();
                applicationCache.put(component.getName(), component);
            }
            return component;
        } catch (Exception e) {
            LOG.error("Error creating application [" + applicationName + "]", e);
        }
        return null;
    }

    public ApplicationComponent createApplication(ApplicationImportContent importContent)
            throws ApplicationException, StorageException {

        ApplicationImporter applicationImporter = new ApplicationImporter(this);
        String applicationName = "unknown";
        try {
            applicationImporter.executeImport(importContent);
            return getApplication(applicationImporter.getApplicationDescriptor().name);
        } catch (ApplicationException ae) {
            throw ae;
        } catch (StorageException se) {
            throw se;
        } catch (Exception e) {
            throw new ApplicationImportCausedException(applicationName, e);
        }
    }

    // StorageImportAdapter implementation

    @Override
    public void checkDescriptor(ApplicationDescriptor applicationDescriptor)
            throws ApplicationException, StorageException {
        String applicationName = applicationDescriptor.name;
        String applicationVersion = applicationDescriptor.version;
        ApplicationComponent appComponent = getApplication(applicationName);
        if (appComponent == null)
            return;
        if (appComponent.hasVersion(applicationVersion))
            throw new ApplicationVersionAlreadyExists(applicationName, applicationVersion);
    }

    @Override
    public StorageApplicationContentAdapter getContentAdapter(String applicationName,
            ApplicationDescriptor applicationDescriptor) throws ApplicationException, StorageException {
        String applicationVersion = applicationDescriptor.version;

        ApplicationComponent applicationComponent = getOrCreateApplication(applicationName);
        try {
            if (applicationComponent.hasVersion(applicationVersion))
                throw new ApplicationVersionAlreadyExists(applicationName, applicationVersion);
            ApplicationVersionComponent versionComponent =
                    applicationComponent.createVersion(applicationVersion);
            versionComponent.setDescriptor(applicationDescriptor);
            versionComponent.init();
            versionComponent.save();
            return versionComponent.adapt();
        } catch (ApplicationException | StorageException rethrow) {
            throw rethrow;
        } catch (Exception e) {
            throw new ApplicationCausedException(applicationName, e);
        }

    }

    @Override
    public EntaxyApplicationVersion getVersion(String applicationName, String version)
            throws ApplicationException, StorageException {
        ApplicationComponent appComp = getApplication(applicationName);
        if (appComp == null)
            return null;
        return appComp.getVersion(version);
    }

}
