/*-
 * ~~~~~~licensing~~~~~~
 * data-mapper-runtime
 * ==========
 * 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.modules.datamapper.resource;

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;

import ru.entaxy.esb.resources.EntaxyResource;
import ru.entaxy.esb.resources.EntaxyResourceProvider;
import ru.entaxy.esb.resources.EntaxyResourceService;
import ru.entaxy.platform.base.support.JSONUtils;
import ru.entaxy.platform.modules.datamapper.AbstractDataMapper;
import ru.entaxy.platform.modules.datamapper.exceptions.DataMapperException;
import ru.entaxy.platform.modules.datamapper.exceptions.KeyNotFoundException;
import ru.entaxy.platform.modules.datamapper.exceptions.MapNotFoundException;

public class ResourceBasedDataMapper extends AbstractDataMapper {

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

    protected String resourceProtocol;

    protected EntaxyResourceProvider resourceProvider;

    protected EntaxyResourceService resourceService;

    protected String path;

    protected String rootUrl;

    // protected String rootLocation;

    protected boolean isInited = false;

    protected boolean mapsLoaded = false;

    EntaxyResource rootResource;

    protected String rootTimestamp = "";

    protected Map<String, String> mapTimestamps = Collections.synchronizedMap(new HashMap<>());

    protected Map<String, Map<String, Object>> mapDataCache = Collections.synchronizedMap(new HashMap<>());

    protected void init() {
        if (isInited)
            return;

        this.resourceProtocol = resourceProvider.getProtocol();

        String rootLocation = String.format("%s/%s", this.path, this.id).replace(":/", ":")
                .replace("//", "/");
        this.rootUrl = String.format("%s:%s", this.resourceProtocol, rootLocation);

        rootResource = resourceService.getResource(rootUrl);
        if (!rootResource.isFolder() && rootResource.exists()) {
            LOG.error("Init failed for DataMapper [{}]: not a folder: [{}]", this.id, this.rootUrl);
            return;
        }

        if (rootResource.exists())
            this.rootTimestamp = rootResource.getTimestamp();

        isInited = true;
    }

    protected void refresh() {

        if (!isInited)
            return;

        rootResource = resourceService.getResource(rootUrl);
        if (!rootResource.exists())
            return;

        if (rootResource.getTimestamp().equals(this.rootTimestamp))
            // up2date
            return;

        List<EntaxyResource> mapResources = resourceService.getResources(rootUrl);

        for (EntaxyResource mapResource : mapResources) {
            String ts = mapResource.getTimestamp();
            String mapName = mapResource.getName();
            if (!mapTimestamps.containsKey(mapName) || !ts.equals(mapTimestamps.get(mapName)))
                reloadMap(mapResource);
        }

    }

    protected void reloadMap(EntaxyResource mapResource) {
        this.mapTimestamps.put(mapResource.getName(), mapResource.getTimestamp());
        String data = mapResource.getAsString();
        JsonObject jsonObject = JSONUtils.getJsonRootObject(data);
        Map<String, Object> mapData = JSONUtils.element2map(jsonObject);
        this.mapDataCache.put(mapResource.getName(), mapData);
    }

    protected void refreshRootResource() {
        rootResource = resourceService.getResource(rootUrl);
    }

    protected void refreshMapList() {
        if (!isInited)
            return;
        refreshRootResource();

        if (!rootResource.exists())
            return;

        if (rootResource.getTimestamp().equals(this.rootTimestamp) && mapsLoaded)
            // up2date
            return;

        List<EntaxyResource> mapResources = getMapResources();

        for (EntaxyResource mapResource : mapResources) {
            String ts = mapResource.getTimestamp();
            String mapName = mapResource.getName();
            if (!mapTimestamps.containsKey(mapName)) {
                this.mapTimestamps.put(mapResource.getName(), "0");
                this.mapDataCache.put(mapResource.getName(), new HashMap<>());
            }
        }

        mapsLoaded = true;

    }

    protected List<EntaxyResource> getMapResources() {
        return resourceService.getResources(rootUrl);
    }

    protected EntaxyResource getMapResource(String mapName) {
        return resourceService.getResource(rootUrl + "/" + mapName);
    }

    protected void refreshMap(String mapName) {
        if (!isInited)
            return;
        EntaxyResource mapResource = getMapResource(mapName);
        if (!mapResource.exists())
            return;
        JsonObject jsonObject = JSONUtils.getJsonRootObject(mapResource.getAsString());
        if (jsonObject == null)
            return;
        Object obj = JSONUtils.element2object(jsonObject);
        if (!(obj instanceof Map))
            return;
        mapDataCache.put(mapName, (Map<String, Object>) obj);
    }

    protected void createMap(String mapName) {
        EntaxyResource mapResource = getMapResource(mapName);
        mapResource.save(new ByteArrayInputStream("{}".getBytes()));
        mapTimestamps.put(mapName, mapResource.getTimestamp());
        mapDataCache.put(mapName, new HashMap<>());
    }

    protected void saveMap(String mapName) {
        if (!mapDataCache.containsKey(mapName)) {
            createMap(mapName);
            return;
        }
        JsonElement jsonElement = JSONUtils.GSON.toJsonTree(mapDataCache.get(mapName));
        if (jsonElement.isJsonObject()) {
            EntaxyResource mapResource = getMapResource(mapName);
            mapResource.save(new ByteArrayInputStream(jsonElement.getAsJsonObject().toString().getBytes()));
        }
    }

    /*
     * DataMapper implementation
     */

    @Override
    public List<String> getMaps() {
        init();
        refreshMapList();
        return new ArrayList<>(mapTimestamps.keySet());
    }

    @Override
    public Object getMapValue(String mapName, Object sourceValue, boolean isTrimForString) throws DataMapperException {
        if (sourceValue == null)
            return null;
        init();
        if (!mapTimestamps.containsKey(mapName))
            refreshMapList();
        if (!mapTimestamps.containsKey(mapName))
            throw new MapNotFoundException(id, mapName);
        refreshMap(mapName);

        if (sourceValue instanceof String && isTrimForString)
            sourceValue = sourceValue.toString().trim();

        if (!mapDataCache.get(mapName).containsKey(sourceValue.toString()))
            throw new KeyNotFoundException(id, mapName, sourceValue.toString());

        return mapDataCache.get(mapName).get(sourceValue.toString());
    }

    @Override
    public void putMapValue(String mapName, Object sourceValue, Object mappedValue) throws DataMapperException {
        if (sourceValue == null)
            return;
        init();
        if (!mapTimestamps.containsKey(mapName))
            refreshMapList();
        if (!mapTimestamps.containsKey(mapName)) {
            // create new map
            createMap(mapName);
        } else {
            refreshMap(mapName);
        }
        mapDataCache.get(mapName).put(sourceValue.toString(), mappedValue);
        saveMap(mapName);
    }

    @Override
    public void removeMapValue(String mapName, Object sourceValue) throws DataMapperException {
        if (sourceValue == null)
            return;
        init();
        if (!mapTimestamps.containsKey(mapName))
            refreshMapList();
        if (!mapTimestamps.containsKey(mapName))
            return;
        refreshMap(mapName);
        mapDataCache.get(mapName).remove(sourceValue.toString());
        saveMap(mapName);
    }

    /*
     * accessors
     */

    public EntaxyResourceProvider getResourceProvider() {
        return resourceProvider;
    }

    public void setResourceProvider(EntaxyResourceProvider resourceProvider) {
        this.resourceProvider = resourceProvider;
    }

    public EntaxyResourceService getResourceService() {
        return resourceService;
    }

    public void setResourceService(EntaxyResourceService resourceService) {
        this.resourceService = resourceService;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }


}
