package org.gcube.application.cms.sdi.model;

import java.util.ArrayList;
import java.util.List;

import org.bson.Document;
import org.gcube.application.cms.plugins.faults.InvalidProfileException;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.HandlerDeclaration;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class MappingObject {
    private String name;
    private String type;
    private String path;

    public void validate() throws InvalidProfileException {
        if (name == null) throw new InvalidProfileException("Invalid mapping " + this + " : name is null");
        if (type == null) throw new InvalidProfileException("Invalid mapping " + this + " : type is null");
        if (path == null) throw new InvalidProfileException("Invalid mapping " + this + " : path is null");
    }

    public static List<MappingObject> getMappingsFromUCD(UseCaseDescriptor ucd, String handlerID) throws InvalidProfileException {
        log.debug("UseCaseDescriptor {} : Evaluating Index schema.. ", ucd.getId());
        HandlerDeclaration handler = ucd.getHandlersMapByID().get(handlerID).get(0);
        log.trace("Handler is {} ",handler);
        Document profileConfiguration = handler.getConfiguration();
        List mappingObjs= profileConfiguration.get("explicitFieldMapping",List.class);
        log.trace("Loading mappings from useCaseDescriptor.. ");
        List<MappingObject> mappingObjects= new ArrayList<>();
        if(mappingObjs!=null){
            for (Object mappingObj : mappingObjs) {
                log.trace("Mapping is {} ",mappingObj);
                MappingObject m = Serialization.convert(mappingObj,MappingObject.class);
                m.validate();
                mappingObjects.add(m);
            }
        }
        return mappingObjects;
    }
}
