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

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.List;

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

import ru.entaxy.platform.integration.applications.ApplicationStorage;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplicationVersion;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationVersionAlreadyExists;
import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponentWithChildren;
import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext;

public class ApplicationComponent
        extends AbstractResourceComponentWithChildren<ApplicationData, ApplicationVersionComponent>
        implements EntaxyApplication {

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

    protected String applicationName;

    protected ApplicationStorage applicationStorage;

    /*
    public ApplicationComponent(EntaxyResourceService resourceService, String applicationName, String parentRootUrl) {
        super(resourceService);
        setEntaxyResourceService(resourceService);
        this.applicationName = applicationName;
        this.rootResourceFolderUrl = parentRootUrl.concat("/").concat(applicationName);
    }
    */

    public ApplicationComponent(ResourceContext resourceContext, String applicationName) {
        super(resourceContext.subcontext(applicationName));
        this.applicationName = applicationName;
    }

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

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

    @Override
    protected ApplicationData createDataObject() {
        return new ApplicationData(applicationName);
    }

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

    @Override
    protected ApplicationVersionComponent createChildComponent(String key) throws Exception {
        return new ApplicationVersionComponent(resourceContext, key, this);
    }

    @Override
    protected List<String> getChildrenKeyList() {
        if (dataObject.versions == null)
            return Collections.emptyList();
        return new ArrayList<>(dataObject.versions.keySet());
    }

    @Override
    protected void addChildKey(String key) {
        dataObject.addVersion(key, Calendar.getInstance().getTimeInMillis() + "");
    }

    @Override
    protected void removeChildKey(String key) {
        dataObject.removeVersion(key);
    }

    @Override
    protected void handleChildLoadException(String key, Exception e) {
        log.error("Error loading version [" + key + "]", e);
    }

    public ApplicationVersionComponent createVersion(String versionNumber) throws Exception {
        if (hasVersion(versionNumber))
            throw new ApplicationVersionAlreadyExists(applicationName, versionNumber);
        ApplicationVersionComponent result = createChildComponent(versionNumber);
        synchronized (childrenCacheLock) {
            dataObject.addVersion(versionNumber);
            updateRootResource();
            childrenCache.put(result);
        }
        return result;
    }

    public ApplicationComponent storage(ApplicationStorage storage) {
        this.applicationStorage = storage;
        return this;
    }

    public boolean hasVersion(String versionNumber) {
        return dataObject.hasVersion(versionNumber);
    }

    /* EntaxyApplication implementation */

    @Override
    public String getName() {
        return applicationName;
    }

    @Override
    public ApplicationStorage getStorage() {
        return this.applicationStorage;
    }

    @Override
    public List<EntaxyApplicationVersion> getVersions() {
        return new ArrayList<>(childrenCache.values());
    }

    @Override
    public EntaxyApplicationVersion getLatestVersion() {
        return childrenCache.get(dataObject.getLatestVersion());
    }

    @Override
    public EntaxyApplicationVersion getVersion(String version) {
        return childrenCache.get(version);
    }

    @Override
    public void removeVersion(String version) {
        try {
            removeChild(version);
        } catch (Exception e) {
            log.error("Error removing version [" + version + "]", e);
        }
    }



}
