/*
 * Created on 27. 7. 2017 12:59:58
 */
package com.jh.radegast.security;

import java.security.Principal;
import java.util.StringJoiner;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jh.common.web.ClientContentModifier;


/**
 * The Class UserInfoModifier.
 *
 * @author Jan Hrabal
 */
public class UserInfoModifier implements ClientContentModifier {

    /** The object mapper. */
    @Autowired
    private ObjectMapper objectMapper;
    
    /** The theme color. */
    @Value("${app.theme.color:#333333}")
    private String themeColor;
    
 
    /**
     * Modify response.
     *
     * @param response the response
     * @param request the request
     * @return the string
     * @see ClientContentModifier.dhl.spms.web.ClientIndexResponseModifier#modifyResponse(java.lang.String, javax.servlet.http.HttpServletRequest)
     */
    @Override
    public String modifyResponse(String response, HttpServletRequest request) {
        Principal p = request.getUserPrincipal();
        if (!(p instanceof Authentication)) {
            return response;
        }

        //bundle
        response = response.replace("<!-- css-bundle -->", String.format("<link rel=\"stylesheet\" type=\"text/css\" href=\"/resources/app.css\"></link>"));
        response = response.replace("<!-- js-bundle -->", String.format("<script type=\"text/javascript\" src=\"/resources/app.js\" defer=\"defer\"></script>"));
        
        if (StringUtils.hasText(themeColor)) {
            StringJoiner sj = new StringJoiner("\n");
            
            sj.add("\t\t<meta name=\"theme-color\" content=\"" + themeColor + "\">");
            sj.add("\t\t<meta name=\"msapplication-navbutton-color\" content=\"" + themeColor + "\">");

            sj.add("\t\t<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">");
            sj.add("\t\t<meta name=\"apple-mobile-web-app-status-bar-style\" content=\"black-translucent\">");
            
            response = response.replace("<!-- meta-tags -->", sj.toString());
        }
        
        try {
            response = response.replace("<!-- user-info -->", String.format("<script type=\"text/javascript\"> window.cfg = %s;</script>", objectMapper.writeValueAsString(p)));
            return response;
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Cannot serialize user info", e);
        }
    }

}
