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

import java.util.List;
import java.util.stream.Collectors;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceMetadata;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.CommonUtils;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProject;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationException;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationNotFoundException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectAlreadyExistsException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectNotFoundException;
import ru.entaxy.platform.integration.applications.exceptions.StorageException;
import ru.entaxy.platform.integration.applications.storage.AbstractApplicationStorage;
import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext;
import ru.entaxy.platform.integration.applications.storage.resource.impl.StorageComponent;
import ru.entaxy.platform.integration.applications.storage.resource.impl.application.ApplicationComponent;
import ru.entaxy.platform.integration.applications.storage.resource.impl.project.ProjectComponent;

public class ResourceBasedStorage extends AbstractApplicationStorage {

    protected String resourceProvider;
    protected String path;

    protected EntaxyResourceService entaxyResourceService;

    protected EntaxyResource rootResourceFolder;
    protected EntaxyResourceMetadata rootResourceFolderMetadata;
    protected EntaxyResourceMetadata.MetadataSection rootMetaStorageSection;

    protected String rootResourceFolderUrl;

    boolean isInited = false;

    protected StorageComponent storageComponent;

    protected ResourceContext rootResourceContext;

    protected interface RootMetaProps {
        String PROP_ENABLED = "enabled";
    }

    public String getResourceProvider() {
        return resourceProvider;
    }

    public void setResourceProvider(String resourceProvider) {
        this.resourceProvider = resourceProvider;
        updateResourceFolderUrl();
        setInfo("provider", this.resourceProvider);
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
        updateResourceFolderUrl();
        setInfo("path", this.path);
    }

    protected void updateResourceFolderUrl() {
        this.rootResourceFolderUrl =
                CommonUtils.getValid(resourceProvider, "").concat(":").concat(CommonUtils.getValid(path, ""));
    }

    public void setEntaxyResourceService(EntaxyResourceService entaxyResourceService) {
        this.entaxyResourceService = entaxyResourceService;
    }

    public void init() {
        rootResourceContext = new ResourceContext();
        rootResourceContext.setEntaxyResourceService(entaxyResourceService);
        rootResourceContext.setRootResourceFolderUrl(rootResourceFolderUrl);
        rootResourceContext.init();
        storageComponent = new StorageComponent(rootResourceContext, name);
        storageComponent.init();
        isInited = true;
    }

    @Override
    public void setEnabled(boolean isEnabled) {
        super.setEnabled(isEnabled);
        if (!isInited)
            return;
        rootMetaStorageSection.getContent().remove(RootMetaProps.PROP_ENABLED);
        rootMetaStorageSection.getContent().addProperty(RootMetaProps.PROP_ENABLED, isEnabled());
        rootResourceFolderMetadata.update();
    }

    protected String getApplicationUrl(String applicationName) {
        return rootResourceFolderUrl.concat("/").concat(applicationName);
    }

    protected boolean projectExists(String projectName) {
        return storageComponent.projectExists(projectName);
    }

    protected boolean applicationExists(String applicationName) {
        return storageComponent.applicationExists(applicationName);
    }

    /* ApplicationStorage implementation */

    @Override
    public String getType() {
        return "resource";
    }

    @Override
    public List<EntaxyApplicationProject> getProjects() {
        return storageComponent.getProjects().stream().map(cmp -> cmp.storage(this))
                .map(cmp -> (EntaxyApplicationProject) cmp).collect(Collectors.toList());
    }

    @Override
    public void addProject(EntaxyApplicationProject project) throws ProjectException, StorageException {
        if (projectExists(project.getName()))
            throw new ProjectAlreadyExistsException(project.getName());
        storageComponent.addProject(project);
    }

    @Override
    public void removeProject(EntaxyApplicationProject project)
            throws ProjectException, StorageException {
        if (project == null)
            throw new ProjectNotFoundException("Unknown");
        if (!projectExists(project.getName()))
            throw new ProjectNotFoundException(project.getName());
        storageComponent.removeProject(project);
    }

    @Override
    public EntaxyApplicationProject createProject(String applicationName)
            throws ProjectException, StorageException {
        if (projectExists(applicationName))
            throw new ProjectAlreadyExistsException(applicationName);
        return storageComponent.createProject(applicationName).storage(this);
    }

    @Override
    public EntaxyApplicationProject getProject(String applicationName) {
        ProjectComponent comp = storageComponent.getProject(applicationName);
        if (comp == null)
            return null;
        return comp.storage(this);
    }

    @Override
    public List<EntaxyApplication> getApplications() {
        return storageComponent.getApplications().stream().map(cmp -> cmp.storage(this))
                .map(cmp -> (EntaxyApplication) cmp).collect(Collectors.toList());
    }

    @Override
    public EntaxyApplication getApplication(String applicationName) {
        ApplicationComponent comp = storageComponent.getApplication(applicationName);
        if (comp == null)
            return null;
        return comp.storage(this);
    }

    @Override
    public void removeApplication(EntaxyApplication application) throws ApplicationException, StorageException {
        if (application == null)
            throw new ApplicationNotFoundException("unknown");
        if (!applicationExists(application.getName()))
            throw new ApplicationNotFoundException(application.getName());
        storageComponent.removeApplication(application);
    }

    @Override
    public EntaxyApplication createApplication(ApplicationImportContent content)
            throws ApplicationException, StorageException {
        return storageComponent.createApplication(content);
    }



}
