/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package performa.form;

import javax.servlet.http.HttpServletRequest;
import oneit.appservices.config.ConfigMgr;
import oneit.security.oauth.form.BaseOAuthLoginFP;
import oneit.servlets.forms.*;
import oneit.utils.CollectionUtils;

/**
 *
 * @author Pradip Sabhadiya
 */
public class LinkedInOAuthLoginFP extends BaseOAuthLoginFP
{
    public static final     String          LINKEDIN_CLIENTID_ATTR_NAME         = "linkedin.clientId";
    public static final     String          LINKEDIN_CLIENTSECRET_ATTR_NAME     = "linkedin.clientSecret";
    
    public static  final   String           LINKEDIN_APP_OAUTH_URL              = "https://www.linkedin.com/oauth/v2/authorization";
    public static  final   String           LINKEDIN_ACCESS_TOKEN_URL           = "https://www.linkedin.com/oauth/v2/accessToken";
    public static  final   String           LINKEDIN_PROFILE_FROM_TOKEN_URL     = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)";
    
    @Override
    public String getOAuthLoginURL(SubmissionDetails submission, String token)
    {
        String appId = ConfigMgr.getKeyfileString(LINKEDIN_CLIENTID_ATTR_NAME);
        
        String callbackURL = getCallbackURL(submission.getRequest());
        
        return LINKEDIN_APP_OAUTH_URL
                + HTTPRequestDetails.getParamStringURL(CollectionUtils.mapEntry("client_id", appId)
                                                                    .mapEntry("redirect_uri", callbackURL)
                                                                    .mapEntry("scope", "r_basicprofile,r_emailaddress")
                                                                    .mapEntry("response_type", "code")
                                                                    .mapEntry("state", token).toMap());
    }
    
    public static String getCallbackURL(HttpServletRequest  request)
    {
        String  urlFirstBit = request.getScheme () + "://" + request.getServerName () + ":" + request.getServerPort ();

        return HTTPRequestDetails.getFullURL(urlFirstBit + request.getContextPath() + "/linkedinCallback", new String[0]);
    }
    
}
