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;

public class LaunchCreateDeepLink  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("deep-link-selection");
//        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;
    }
}
