package com.sample.token;

import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.Application;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.impl.utils.APIUtil;
import org.wso2.carbon.apimgt.keymgt.issuers.APIMTokenIssuer;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oauth2.model.RequestParameter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MyAPIMTokenIssuer extends APIMTokenIssuer {

	private static final Log log = LogFactory.getLog(MyAPIMTokenIssuer.class);

	@Override
	public String accessToken(OAuthTokenReqMessageContext tokReqMsgCtx) throws OAuthSystemException {

		// generate access token using super method
		String accessToken = super.accessToken(tokReqMsgCtx);

		String clientId = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getClientId();
		Application application;
		try {
			application = APIUtil.getApplicationByClientId(clientId);
			String tokenType = application.getTokenType();

			// only acceptable for opaque access tokens and not JWT tokens
			if (!APIConstants.JWT.equals(tokenType)) {
				
				// retrieve all request parameters sent to the token request
				RequestParameter[] reqParams = tokReqMsgCtx.getOauth2AccessTokenReqDTO().getRequestParameters();
				for (int i = 0; i < reqParams.length; i++) {

					// check for devhash parameter from the request parameters and append it to the
					// access token
					if ("devhash".equals(reqParams[i].getKey())) {
						accessToken += reqParams[i].getValue()[0];
						break;
					}
				}
			}
		} catch (APIManagementException e) {
			log.error("Exception occured in my piece of code ", e);
		}

		return accessToken;
	}
}