package org.gcube.application.cms.sdi.engine.bboxes;

import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.JSONPathWrapper;
import org.gcube.application.geoportal.common.model.document.filesets.sdi.GCubeSDILayer;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;

import java.util.List;

@Slf4j
public class BBOXPathScanner extends BBOXEvaluator{


    public BBOXPathScanner() {
        super("BBOX PATH SCANNER");
    }

    @Override
    public boolean isConfigured(Document profileConfiguration) {
        return profileConfiguration.containsKey("bboxEvaluation");
    }

    @Override
    public GCubeSDILayer.BBOX evaluate(Document profileConfiguration, UseCaseDescriptor useCaseDescriptor, JSONPathWrapper documentNavigator) {
        List bboxEvaluationPaths = profileConfiguration.get("bboxEvaluation",List.class);
        GCubeSDILayer.BBOX toSet = null;
        for(Object pathObj : bboxEvaluationPaths){
            log.debug("UseCaseDescriptor {} : Evaluating path {} ", useCaseDescriptor.getId(),pathObj);
            List<Object> bboxObjects = documentNavigator.getByPath(pathObj.toString());
            log.debug("UseCaseDescriptor {} : Evaluating path {} .. results {} ", useCaseDescriptor.getId(),pathObj,bboxObjects);
            for(Object bboxObject  : bboxObjects) {
                log.info("Matched path {}, value is {} ",pathObj.toString(),bboxObject);
                GCubeSDILayer.BBOX box = Serialization.convert(bboxObject, GCubeSDILayer.BBOX.class);

                if(toSet == null) toSet = box;
                if(box.getMaxX()>toSet.getMaxX()) toSet.setMaxX(box.getMaxX());
                if(box.getMaxY()>toSet.getMaxY()) toSet.setMaxY(box.getMaxY());

                if(box.getMinX()<toSet.getMinX()) toSet.setMinX(box.getMinX());
                if(box.getMinY()<toSet.getMinY()) toSet.setMinY(box.getMinY());
            }
        }
        return toSet;
    }
}
