package org.gcube.application.geoportal.client.utils;

import org.apache.commons.io.IOUtils;
import org.bson.Document;
import org.gcube.application.geoportal.common.model.rest.QueryRequest;
import org.gcube.application.geoportal.common.utils.Files;

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

public class Queries {


    public static QueryRequest parse(String json) throws IOException {
        Document queryDocument=Document.parse(json);
        QueryRequest req=new QueryRequest();
        if(queryDocument.containsKey("ordering"))
            req.setOrdering(Serialization.read(((Document)queryDocument.get("ordering")).toJson(),QueryRequest.OrderedRequest.class));
        if(queryDocument.containsKey("paging"))
            req.setPaging(Serialization.read(((Document)queryDocument.get("paging")).toJson(),QueryRequest.PagedRequest.class));
        req.setProjection(queryDocument.get("projection",Document.class));
        req.setFilter(queryDocument.get("filter",Document.class));

        return req;
    };

    public static QueryRequest readPath(String jsonFilePath) throws IOException{
        return parse(Files.readFileAsString(jsonFilePath, Charset.defaultCharset()));
    }

    public static QueryRequest readFile(File jsonFile)throws IOException{
        return parse(Files.readFileAsString(jsonFile.getAbsolutePath(), Charset.defaultCharset()));
    }
    public static  QueryRequest read(InputStream is)throws IOException{
        return parse(IOUtils.toString(is));
    }
}
