/*-
 * ~~~~~~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.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.base.support.CommonUtils;
import ru.entaxy.platform.integration.applications.ApplicationProjectContent.STANDARD_PROPERTIES;
import ru.entaxy.platform.integration.applications.ApplicationProjectInfo;
import ru.entaxy.platform.integration.applications.ApplicationStorage;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProject;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionCausedException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionNotFoundException;
import ru.entaxy.platform.integration.applications.storage.resource.impl.AbstractResourceComponentWithChildren;
import ru.entaxy.platform.integration.applications.storage.resource.impl.ResourceContext;

public class ProjectComponent extends AbstractResourceComponentWithChildren<ProjectData, ProjectVersionComponent>
        implements EntaxyApplicationProject {

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

    protected static String extractProjectName(String projectFullName) {
        int index = projectFullName.indexOf('/');
        if (index < 0)
            return projectFullName;
        return projectFullName.substring(index + 1);
    }

    protected String projectName;

    protected String group;

    protected ApplicationStorage applicationStorage;

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

    public ProjectComponent(ResourceContext parentResourceContext, String projectFullName) {
        super(parentResourceContext.subcontext(extractProjectName(projectFullName)));
        setProjectName(projectFullName);
    }

    protected void setProjectName(String projectFullName) {
        int index = projectFullName.indexOf('/');
        if (index > 0) {
            this.projectName = projectFullName.substring(index + 1);
            setGroup(projectFullName.substring(0, index));
        } else {
            this.projectName = projectFullName;
            setGroup(null);
        }
    }

    protected void setGroup(String group) {
        if (!CommonUtils.isValid(group))
            this.group = EntaxyApplication.DEFAULT_GROUP_ID;
        else
            this.group = group;
    }

    @Override
    public void init() {
        super.init();
        this.group = dataObject.group;
    }

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

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

    @Override
    protected ProjectData createDataObject() {
        return new ProjectData(projectName, group);
    }

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

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

    @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 ProjectComponent storage(ApplicationStorage storage) {
        this.applicationStorage = storage;
        return this;
    }

    /* EntaxyApplicationProject implementation */

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

    @Override
    public String getGroup() {
        return group;
    }

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

    @Override
    public void save() {
        // TODO Auto-generated method stub

    }

    @Override
    public void disgard() {
        // TODO Auto-generated method stub

    }

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

    @Override
    public EntaxyApplicationProjectVersion getLatestVersion() {
        String latest = dataObject.getLatestVersion();
        if (latest == null)
            return null;
        return getVersion(latest);
    }

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

    @Override
    public EntaxyApplicationProjectVersion createVersion(String version) throws ProjectVersionException {
        try {
            return createNewChild(version);
        } catch (Exception e) {
            log.error("Error creating version [" + version + "]", e);
            if (e instanceof ProjectVersionException)
                throw (ProjectVersionException) e;
            throw new ProjectVersionCausedException(projectName, version, e);
        }
    }

    @Override
    public EntaxyApplicationProjectVersion createVersion(String version, String fromVersion)
            throws ProjectVersionException {
        ProjectVersionComponent sourceVersion = childrenCache.get(fromVersion);
        if (sourceVersion == null)
            throw new ProjectVersionNotFoundException(projectName, fromVersion);
        try {
            ProjectVersionComponent newVersion = createNewChild(version);
            newVersion.updateFromString(sourceVersion.getAsJsonString());
            newVersion.getProperties().put(STANDARD_PROPERTIES.CREATED_ON,
                    Calendar.getInstance().getTimeInMillis() + "");
            newVersion.save();
        } catch (Exception e) {
            log.error("Error creating version [" + version + "]", e);
            if (e instanceof ProjectVersionException)
                throw (ProjectVersionException) e;
            throw new ProjectVersionCausedException(projectName, version, e);
        }
        return null;
    }

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

    @Override
    public ApplicationProjectInfo getInfo() {
        // TODO Auto-generated method stub
        return null;
    }



}
