package org.gcube.application.cms.plugins.requests;

import lombok.*;
import org.bson.Document;
import org.gcube.application.cms.plugins.faults.InvalidPluginRequestException;
import org.gcube.application.cms.serialization.Serialization;
import org.gcube.application.geoportal.common.model.document.accounting.Context;
import org.gcube.application.geoportal.common.model.document.accounting.User;
import org.gcube.application.geoportal.common.model.useCaseDescriptor.UseCaseDescriptor;

@Getter
@Setter
@ToString(callSuper = true)
@RequiredArgsConstructor
public class BaseRequest {

    @NonNull
    UseCaseDescriptor useCaseDescriptor;
    @NonNull
    User caller;
    @NonNull
    Context context;


    Document callParameters;

    public final String getMandatory(String param) throws InvalidPluginRequestException {
        return getMandatory(param,callParameters);
    }

    public final String getWithDefault(String param,String defaultValue) {
        try{
            return getMandatory(param,callParameters);
        }catch (InvalidPluginRequestException e){
            return defaultValue;
        }
    }

    public static final String getMandatory(String param,Document params) throws InvalidPluginRequestException {
        if(params==null || params.isEmpty()|| !params.containsKey(param)) throw new InvalidPluginRequestException("Missing mandatory parameter "+param);
        return Serialization.convert(params.get(param),String.class);
    }

    public BaseRequest validate() throws InvalidPluginRequestException {
        if(useCaseDescriptor ==null)throw new InvalidPluginRequestException("UseCaseDescriptor cannot be null ");
        return this;
    }

    public BaseRequest setParameter(String key,Object value){
        if(callParameters==null) callParameters=new Document();
        callParameters.put(key, value);
        return this;
    }
}
