package riomhaire.lti.core.business.commands;

import org.springframework.web.servlet.ModelAndView;
import riomhaire.lti.core.model.LTIMessage;
import riomhaire.lti.core.model.interfaces.ApplicationRegistry;
import riomhaire.lti.core.model.interfaces.Command;

import java.util.HashMap;
import java.util.function.Function;

/**
 * Defines  execute command on message P within environment E returning T
 *
 * @param <T> What object is returned by the command
 * @param <E> WHat execution environment is to be used (usually some form of Application Registry)
 * @param <P> The message the command can process
 *
 * This is what should render or redirect to the actual content. In this case we just pretty-print what was sent as
 * metadata and what claims are in the JWT
 */
public class LaunchContentCommand implements Command<ModelAndView, ApplicationRegistry<ModelAndView,LTIMessage>, LTIMessage> {

    @Override
    public ModelAndView execute(ApplicationRegistry<ModelAndView,LTIMessage> environment, LTIMessage message) {
        final String prefix = "https://purl.imsglobal.org/spec/lti/claim/";
        var simplifiedClaims = new HashMap<String, Object>();
        var mav = new ModelAndView("dump-launch");
//        var mav = new ModelAndView("redirect:https://www.riomhaire.com");

        // Strip "https://purl.imsglobal.org/spec/lti/claim/" from keys
        Function<String, String> simplifier = s -> {
            if (s != null && s.startsWith(prefix)) {
                return s.substring(prefix.length());
            }
            return s;
        };
        message.getClaims().forEach((s, o) -> simplifiedClaims.put(simplifier.apply(s), o));
        mav.addObject("claims", simplifiedClaims);
        mav.addObject("metadata", message.getMetadata());

        return mav;
    }
}
