/*
 * Copyright 2014-2015 the original author or authors.
 *
 * 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.lastaflute.web.callback;

import org.lastaflute.web.response.ActionResponse;
import org.lastaflute.web.response.JsonResponse;
import org.lastaflute.web.servlet.request.RequestManager;

/**
 * @author jflute
 * @since 0.6.0 (2015/07/05 Sunday at maihama)
 */
public class CrossOriginResourceSharing {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    protected final RequestManager requestManager;
    protected final String allowOrigin;

    // ===================================================================================
    //                                                                         Constructor
    //                                                                         ===========
    public CrossOriginResourceSharing(RequestManager requestManager, String allowOrigin) {
        assertArgumentNotNull("requestManager", requestManager);
        assertArgumentNotNull("allowOrigin", allowOrigin);
        this.requestManager = requestManager;
        this.allowOrigin = allowOrigin;
    }

    // ===================================================================================
    //                                                                               Share
    //                                                                               =====
    public ActionResponse share() {
        return isTargetRequest() ? createAllowResponse() : ActionResponse.undefined();
    }

    protected ActionResponse createAllowResponse() {
        final ActionResponse response = newAllowResponse();
        response.header("Access-Control-Allow-Origin", prepareAllowOrigin());
        response.header("Access-Control-Allow-Methods", prepareAllowMethods());
        response.header("Access-Control-Max-Age", String.valueOf(prepareMaxAge()));
        response.header("Access-Control-Allow-Headers", prepareAllowHeaders());
        response.header("Access-Control-Allow-Credentials", prepareAllowCredentials());
        return response;
    }

    protected ActionResponse newAllowResponse() {
        return JsonResponse.asEmptyBody();
    }

    protected boolean isTargetRequest() {
        return requestManager.getRequest().getMethod().equals("OPTIONS");
    }

    protected String prepareAllowOrigin() {
        return allowOrigin;
    }

    protected String prepareAllowMethods() {
        return "GET, POST, OPTIONS, DELETE, PUT";
    }

    protected int prepareMaxAge() { // seconds
        return 3600; // as default
    }

    protected String prepareAllowHeaders() {
        return "Origin, Content-Type, Accept, Authorization";
    }

    protected String prepareAllowCredentials() {
        return "true";
    }

    // ===================================================================================
    //                                                                        Small Helper
    //                                                                        ============
    protected void assertArgumentNotNull(String variableName, Object value) {
        if (variableName == null) {
            throw new IllegalArgumentException("The variableName should not be null.");
        }
        if (value == null) {
            throw new IllegalArgumentException("The argument '" + variableName + "' should not be null.");
        }
    }
}

@@ -651,16 +651,65 @@
 lback;%0A%0A
+import java.util.HashMap;%0Aimport java.util.Map;%0A%0A
 import o
@@ -857,16 +857,75 @@
 Manager;
+%0Aimport org.lastaflute.web.servlet.request.ResponseManager;
 %0A%0A/**%0A *
@@ -2301,85 +2301,503 @@
     
-return isTargetRequest() ? createAllowResponse() : ActionResponse.undefined()
+if (isTargetRequest()) %7B%0A            return createPreflightResponse();%0A        %7D else %7B%0A            return handleRealResponse();%0A        %7D%0A    %7D%0A%0A    protected boolean isTargetRequest() %7B%0A        return requestManager.getRequest().getMethod().equals(%22OPTIONS%22);%0A    %7D%0A%0A    protected ActionResponse createPreflightResponse() %7B%0A        final ActionResponse response = newAllowResponse();%0A        prepareAllowHeaderMap().forEach((key, value) -%3E response.header(key, value));%0A        return response
 ;%0A  
@@ -2830,22 +2830,19 @@
 esponse 
-create
+new
 AllowRes
@@ -2863,83 +2863,701 @@
     
-final ActionResponse response = newAllowResponse();%0A        response.header
+return JsonResponse.asEmptyBody();%0A    %7D%0A%0A    protected ActionResponse handleRealResponse() %7B%0A        final ResponseManager responseManager = requestManager.getResponseManager();%0A        prepareAllowHeaderMap().forEach((key, value) -%3E responseManager.addHeader(key, value));%0A        return ActionResponse.undefined(); // only header setup here%0A    %7D%0A%0A    // -----------------------------------------------------%0A    //                                          Allow Header%0A    //                                          ------------%0A    protected Map%3CString, String%3E prepareAllowHeaderMap() %7B%0A        final Map%3CString, String%3E headerMap = new HashMap%3CString, String%3E(5);%0A        headerMap.put
 (%22Ac
@@ -3611,39 +3611,37 @@
 ));%0A        
-response.header
+headerMap.put
 (%22Access-Con
@@ -3689,39 +3689,37 @@
 ));%0A        
-response.header
+headerMap.put
 (%22Access-Con
@@ -3771,39 +3771,37 @@
 ));%0A        
-response.header
+headerMap.put
 (%22Access-Con
@@ -3853,31 +3853,29 @@
         
-response.header
+headerMap.put
 (%22Access
@@ -3950,239 +3950,17 @@
 urn 
-response;%0A    %7D%0A%0A    protected ActionResponse newAllowResponse() %7B%0A        return JsonResponse.asEmptyBody();%0A    %7D%0A%0A    protected boolean isTargetRequest() %7B%0A        return requestManager.getRequest().getMethod().equals(%22OPTIONS%22)
+headerMap
 ;%0A  

add headers to all response if cross origin