/* Copyright 2008 we-lab-doc! (http://www.we-lab-doc.com/)
 *
 * 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 com.we_lab_doc.spacecard.utils
 
import org.apache.log4j.Logger
import org.springframework.web.context.request.RequestContextHolder as RCH

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: February 26, 2008
 */ 
class RequestUtils {
	private RequestUtils() {}
	static log = Logger.getLogger("grails.app.utils.RequestUtils")	
	
	static boolean bTestingMode = false	
	static def setTestingMode() {
		bTestingMode = true
	}
	
	static String getURI(request)  {
		if(bTestingMode) return "<test-mode-uri>"
		def uri = (String) request.getAttribute( "javax.servlet.forward.request_uri" )
		if(!uri) {
			uri = request.getRequestURI()
		}
		def queryString = request.getQueryString()
		return queryString != null && queryString.length() > 0 ? uri + "?" + queryString : uri
	}

	static String getProtocolAndHostAndPort(request) {
		if(bTestingMode) return "<test-mode-ProtocolAndHostAndPort>"
		URL url = new URL(request.getRequestURL().toString())
		return "${url.getProtocol()}://${url.getHost()}:${url.getPort()}"
	}


	static String getExternalIpForLogging() {
		def webRequest = RCH.currentRequestAttributes()
		return getExternalIp(webRequest) 
	}
	static String getExternalIp(request) {
		if(bTestingMode) return "<test-mode-ip>"
				
		if(request == null) return null
		// TODO 試行錯誤中
		def x_forwarded_for = request.getHeader("x-forwarded-for")
		def intel_source_ip = request.getHeader("INTEL_SOURCE_IP")
		def wl_proxy_client_ip = request.getHeader("WL_Proxy-Client-IP")
		def remoteAddr = request.getRemoteAddr()
		def remoteHost = request.getRemoteHost()
		log.debug("-----------------------------------------")
		log.debug("x-forwarded-for: ${x_forwarded_for}")
		log.debug("INTEL_SOURCE_IP: ${intel_source_ip}")
		log.debug("WL_Proxy-Client-IP: ${wl_proxy_client_ip}")
		log.debug("REMOTE_ADDR: ${remoteAddr}")
		log.debug("REMOTE_HOST: ${remoteHost}")
		def ip
		if ( (!x_forwarded_for) || x_forwarded_for.length() < 4 ) {
			if ( (!intel_source_ip) || intel_source_ip.length() < 4 ) {
				if ( (!wl_proxy_client_ip) || wl_proxy_client_ip.length() < 4 ){
					ip = remoteAddr == remoteHost ? remoteAddr : "${remoteAddr}(${remoteHost})"
				} else {
					ip = wl_proxy_client_ip 
				}
			} else {
				ip = intel_source_ip				
			}
		} else {
			ip = x_forwarded_for
		}
		return selected_(ip)
	}
	private String selected_(str) {
		log.debug("##selected: ${str}")
		log.debug("-----------------------------------------")		
		return str
	}
	
}