/*
 *
 *  Copyright (c) 2019, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

package org.wso2.carbon.apimgt.rest.api.store.v1.mappings;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import org.wso2.carbon.apimgt.api.model.APIKey;
import org.wso2.carbon.apimgt.api.model.ApplicationConstants;
import org.wso2.carbon.apimgt.impl.APIConstants;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyDTO;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyGenerateRequestDTO;
import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationTokenDTO;
import org.wso2.carbon.apimgt.rest.api.util.exception.InternalServerErrorException;

import java.util.Arrays;
import java.util.Map;

public class ApplicationKeyMappingUtil {

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

    @SuppressWarnings("unchecked")
    public static ApplicationKeyDTO fromApplicationKeyToDTO(Map<String, Object> keyDetails, String applicationKeyType) {
        ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
        applicationKeyDTO.setConsumerKey((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_KEY));
        applicationKeyDTO
                .setConsumerSecret((String) keyDetails.get(APIConstants.FrontEndParameterNames.CONSUMER_SECRET));
        applicationKeyDTO.setKeyState((String) keyDetails.get(APIConstants.FrontEndParameterNames.KEY_STATE));
        try {
            String appDetailsString = (String) keyDetails.get(ApplicationConstants.OAUTH_APP_DETAILS);
            if (appDetailsString != null) {
                JSONObject appDetailsJsonObj = (JSONObject) new JSONParser().parse(appDetailsString);
                if (appDetailsJsonObj != null) {
                    applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(applicationKeyType));
                    String supportedGrantTypes = (String) appDetailsJsonObj
                            .get(ApplicationConstants.OAUTH_CLIENT_GRANT);
                    if (supportedGrantTypes != null) {
                        applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(supportedGrantTypes.split(" ")));
                    }
                    String callbackUrl = (String) appDetailsJsonObj.get(ApplicationConstants.OAUTH_REDIRECT_URIS);
                    applicationKeyDTO.setCallbackUrl(callbackUrl);
                }
            }

            ApplicationTokenDTO tokenDTO = new ApplicationTokenDTO();
            tokenDTO.setValidityTime((Long)keyDetails.get(APIConstants.AccessTokenConstants.VALIDITY_TIME));
            tokenDTO.setAccessToken((String)keyDetails.get(APIConstants.AccessTokenConstants.ACCESS_TOKEN));
            String[] tokenScopes = (String[])keyDetails.get(APIConstants.AccessTokenConstants.TOKEN_SCOPES);
            if (tokenScopes != null) {
                tokenDTO.setTokenScopes(Arrays.asList(tokenScopes));
            }

            applicationKeyDTO.setToken(tokenDTO);
        } catch (ParseException e) {
            String errorMsg = "Error while parsing application details string";
            log.error(errorMsg, e);
            throw new InternalServerErrorException(errorMsg, e);
        }
        return applicationKeyDTO;
    }

    public static ApplicationKeyDTO fromApplicationKeyToDTO(APIKey apiKey) {
        ApplicationKeyDTO applicationKeyDTO = new ApplicationKeyDTO();
        applicationKeyDTO.setKeyType(ApplicationKeyDTO.KeyTypeEnum.valueOf(apiKey.getType()));
        applicationKeyDTO.setConsumerKey(apiKey.getConsumerKey());
        applicationKeyDTO.setConsumerSecret(apiKey.getConsumerSecret());
        applicationKeyDTO.setKeyState(apiKey.getState());
        if (apiKey.getGrantTypes() != null) {
            applicationKeyDTO.setSupportedGrantTypes(Arrays.asList(apiKey.getGrantTypes().split(" ")));
        } else {
            applicationKeyDTO.setSupportedGrantTypes(null);
        }
        applicationKeyDTO.setCallbackUrl(apiKey.getCallbackUrl());

        ApplicationTokenDTO tokenDTO = new ApplicationTokenDTO();
        if (apiKey.getTokenScope() != null) {
            tokenDTO.setTokenScopes(Arrays.asList(apiKey.getTokenScope().split(" ")));
        }
        tokenDTO.setAccessToken(apiKey.getAccessToken());
        tokenDTO.setValidityTime(apiKey.getValidityPeriod());
        applicationKeyDTO.setToken(tokenDTO);
        return applicationKeyDTO;
    }

}

@@ -1149,94 +1149,8 @@
 TO;%0A
-import org.wso2.carbon.apimgt.rest.api.store.v1.dto.ApplicationKeyGenerateRequestDTO;%0A
 impo
@@ -1214,24 +1214,24 @@
 onTokenDTO;%0A
+
 import org.w
@@ -1351,16 +1351,91 @@
 l.Map;%0A%0A
+/**%0A * Utility class for application key generation related operations%0A */%0A
 public c
@@ -1552,24 +1552,286 @@
 il.class);%0A%0A
+    /**%0A     * Insert the application related details to a DTO Object%0A     *%0A     * @param keyDetails application related details map%0A     * @param applicationKeyType key type of the application%0A     * @return DTO object with application related details%0A     */%0A
     @Suppres
@@ -3503,16 +3503,17 @@
 e((Long)
+ 
 keyDetai
@@ -3614,16 +3614,17 @@
 (String)
+ 
 keyDetai
@@ -3725,16 +3725,17 @@
 tring%5B%5D)
+ 
 keyDetai
@@ -4228,24 +4228,260 @@
 DTO;%0A    %7D%0A%0A
+    /**%0A     * Insert the application related details to a DTO Object using api key%0A     *%0A     * @param apiKey object that contains details needed during token request%0A     * @return DTO object with application related details%0A     */%0A
     public s
@@ -5623,17 +5623,16 @@
 KeyDTO;%0A
+
     %7D%0A
-%0A
 %7D%0A

format code and add comments