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

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

import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.osgi.service.component.annotations.ReferenceCardinality;
import org.osgi.service.component.annotations.ReferencePolicy;
import org.osgi.service.component.annotations.ReferencePolicyOption;

import ru.entaxy.platform.integration.applications.ApplicationManager;
import ru.entaxy.platform.integration.applications.ApplicationStorage;
import ru.entaxy.platform.integration.applications.ApplicationStorage.ApplicationImportContent;
import ru.entaxy.platform.integration.applications.EntaxyApplication;
import ru.entaxy.platform.integration.applications.EntaxyApplicationProjectVersion;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationException;
import ru.entaxy.platform.integration.applications.exceptions.ApplicationImportCausedException;
import ru.entaxy.platform.integration.applications.exceptions.StorageException;
import ru.entaxy.platform.integration.applications.exceptions.StorageNotEnabledException;
import ru.entaxy.platform.integration.applications.exceptions.StorageNotFoundException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionBuildNotAvailable;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionCausedException;
import ru.entaxy.platform.integration.applications.exceptions.ProjectVersionException;

@Component(service = ApplicationManager.class, immediate = true)
public class ApplicationManagerImpl implements ApplicationManager {

    protected Map<String, ApplicationStorage> storages = new HashMap<>();
    protected Object storagesLock = new Object();

    @Reference(cardinality = ReferenceCardinality.MANDATORY, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY)
    volatile ExportImportHelper exportImportHelper;

    @Reference(cardinality = ReferenceCardinality.MULTIPLE, policy = ReferencePolicy.DYNAMIC,
            policyOption = ReferencePolicyOption.GREEDY, unbind = "unregisterStorage")
    public void registerStorage(ApplicationStorage storage) {
        synchronized (storagesLock) {
            storages.put(storage.getName(), storage);
        }
    }

    public void unregisterStorage(ApplicationStorage storage) {
        synchronized (storagesLock) {
            storages.remove(storage.getName());
        }
    }

    protected ApplicationStorage getStorageUnsafe(String storageName) throws StorageException {
        ApplicationStorage storage = storages.get(storageName);
        if (storage == null)
            throw new StorageNotFoundException(storageName);
        if (!storage.isEnabled())
            throw new StorageNotEnabledException(storageName);
        return storage;
    }

    /* ApplicationManager implementation */

    @Override
    public ApplicationStorage getStorage(String storageName) {
        return storages.get(storageName);
    }

    @Override
    public List<ApplicationStorage> getAllStorages() {
        return new ArrayList<>(storages.values());
    }

    @Override
    public void addStorage(ApplicationStorage applicationStorage) {
        // TODO Auto-generated method stub

    }

    @Override
    public void removeStorage(ApplicationStorage applicationStorage) {
        // TODO Auto-generated method stub

    }

    @Override
    public void exportToFile(EntaxyApplicationProjectVersion version, String filePath) throws ProjectVersionException {
        if (!version.isBuildAvailable())
            throw new ProjectVersionBuildNotAvailable(version.getApplication().getName(), version.getVersionNumber());
        Map<String, Object> props = new HashMap<>();
        props.put("filePath", filePath);
        try {
            exportImportHelper.doExport(version, "file", props);
        } catch (ProjectVersionException ve) {
            throw ve;
        } catch (Exception e) {
            throw new ProjectVersionCausedException(version.getApplication().getName(), version.getVersionNumber(), e);
        }
    }

    @Override
    public void exportToRepository(EntaxyApplicationProjectVersion version, String repositoryName)
            throws ProjectVersionException {
        if (!version.isBuildAvailable())
            throw new ProjectVersionBuildNotAvailable(version.getApplication().getName(), version.getVersionNumber());
        Map<String, Object> props = new HashMap<>();
        props.put("repositoryName", repositoryName);
        try {
            exportImportHelper.doExport(version, "repository", props);
        } catch (ProjectVersionException ve) {
            throw ve;
        } catch (Exception e) {
            throw new ProjectVersionCausedException(version.getApplication().getName(), version.getVersionNumber(), e);
        }
    }

    @Override
    public EntaxyApplication importApplicationFromFile(String storageName, String filePath)
            throws ApplicationException, StorageException {
        Map<String, Object> props = new HashMap<>();
        props.put("filePath", filePath);
        try {
            ApplicationImportContent result = exportImportHelper.doImport("file", props);
            return createApplicationFromImport(storageName, result);
        } catch (Exception e) {
            throw new ApplicationImportCausedException(filePath, e);
        }
    }

    @Override
    public EntaxyApplication importApplicationFromRepository(String storageName, String mavenUrl)
            throws ApplicationException, StorageException {
        Map<String, Object> props = new HashMap<>();
        props.put("mavenUrl", mavenUrl);
        try {
            ApplicationImportContent result = exportImportHelper.doImport("repository", props);
            return createApplicationFromImport(storageName, result);
        } catch (Exception e) {
            throw new ApplicationImportCausedException(mavenUrl, e);
        }
    }

    protected EntaxyApplication createApplicationFromImport(String storageName, ApplicationImportContent importContent)
            throws Exception {
        ApplicationStorage storage = getStorageUnsafe(storageName);
        EntaxyApplication result = storage.createApplication(importContent);
        importContent.clear();
        return result;
    }

}
