package com.capgemini.reports.common.obtaindata;

import com.capgemini.framework.teamcenter.authent.TcSession;
import com.capgemini.framework.teamcenter.exceptions.KurtException;
import com.capgemini.framework.teamcenter.policies.PolicyLocation;
import com.capgemini.reports.common.AbstractKurtServlet;
import com.capgemini.reports.common.ServletMessageHelper;
import com.capgemini.reports.exceptions.InvalidUserInputException;
import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;

import javax.servlet.http.HttpServletRequest;

/**
 * Abstract class providing the framework for request of ajax client.
 */
@Slf4j
public abstract class AbstractObtainDataServlet extends AbstractKurtServlet {

    private static final long serialVersionUID = 7803067312625585174L;

    @Override
    protected JSONObject perform(final HttpServletRequest request, final TcSession session) throws InvalidUserInputException {
        try {
            PolicyLocation policyLocation = obtainLocation();
            session.setObjectPropPolicy(policyLocation);
        } catch (KurtException e) {
            log.error("Unable to findAll data for request Ajax Client", e);
            return ServletMessageHelper.errorMessage("Impossible de retrouver les données, merci de contacter l'administrateur système.");
        }
        return obtainData(request, session);
    }

    /**
     * The main method of this class: sets up the environment required to valdiate user input before a report execution.
     *
     * @param request the web request containing various user inputs
     * @param session a Tc session to validate the input
     * @return a {@link JSONObject} containing this server's response to the browser
     * @throws InvalidUserInputException thrown when user posted invalid input parameters
     */
    protected abstract JSONObject obtainData(final HttpServletRequest request, final TcSession session) throws InvalidUserInputException;

    /**
     * Returns the {@link PolicyLocation} of the policy to be used to perform some validation on the user inputs.
     *
     * @return the {@link PolicyLocation}
     */
    protected abstract PolicyLocation obtainLocation();
}
