package org.gcube.application.geoportal.service.engine.providers.ucd;

import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.extern.slf4j.Slf4j;
import org.gcube.application.cms.caches.AbstractScopedMap;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.rest.ConfigurationException;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;
import org.gcube.application.geoportal.common.utils.Files;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
public class LocalFolderProfileMapCache extends AbstractScopedMap<ProfileMap> {

	String folderPath = null;

	public LocalFolderProfileMapCache(String folderPath) {
		super("Local Profiles CACHE");
		this.folderPath=folderPath;
	}

	@Override
	public void init() {
	}

	@Override
	protected void dispose(ProfileMap toDispose) {

	}


	@Override
	protected ProfileMap retrieveObject(String context) throws ConfigurationException {


		// Load from resources
		ProfileMap toReturn=new ProfileMap();

		try {
			log.debug("Loading from {} ",folderPath);
			File baseFolder = new File (folderPath);
			for (File file : baseFolder.listFiles(pathname -> pathname.getName().endsWith(".json"))) {
				try {
					String jsonString = Files.readFileAsString(file.getAbsolutePath(), Charset.defaultCharset());
					log.trace("JSON IS {}",jsonString);
					UseCaseDescriptor p = Serialization.read(jsonString, UseCaseDescriptor.class);
					toReturn.put(p.getId(),p);
				} catch (JsonProcessingException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}catch(Throwable t){
			t.printStackTrace();
		}

		return toReturn;

	}

}
