/* 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

/**
 * @author Shigeru GOUGI
 * @since 0.1
 *        <p/>
 *        Created: March 17, 2008
 */
final class PaginateUtils {
	static Map getPaginateParamsOnly(params) {
		def rtParams = [:]
		if(params?.max)	rtParams.max = params.max
		if(params?.offset) rtParams.offset = params.offset
		return rtParams
	}
	static Map getOrderParamsOnly(params) {
		def rtParams = [:]
		if(params?.sort) rtParams.sort = params.sort		
		if(params?.order) rtParams.order = params.order
		return rtParams
	}
	static Map sanitizeParams(params) {
		def rtParams = [:]
		if(params?.max)	{
			try {
				rtParams.max = Integer.parseInt("${params.max}")
			} catch(e) {
				rtParams.max = 10 // 適当
			}
		}
		if(params?.offset){
			try {
				rtParams.offset = Integer.parseInt("${params.offset}")
			} catch(e) {
				rtParams.offset = 0
			}
		}
		if(params?.sort) rtParams.sort = params.sort
		if(params?.order) rtParams.order = params.order
		return rtParams
	}
	static Map makeSelectParams(Map params, Map mappings) {
		def aParams = sanitizeParams(params)
   		def rtMap = [:]
        rtMap.put("args", getPaginateParamsOnly(aParams))
        if(mappings) rtMap.args.putAll(mappings)
        rtMap.put("orderByClause", makeOrderByClause(aParams))
        return rtMap
	}
	static Map makeParams(params, defaultMax, defaultSort, defaultOrder) {
		def aParams = sanitizeParams(params)
        if(!aParams.max && defaultMax) {
        	try {
        		aParams.max = Integer.parseInt("${defaultMax}")
        	} catch(e) {
        		assert false // bug
        	}
        }
        if((!aParams.sort) && defaultSort)
	    	aParams.sort = defaultSort
        if((!aParams.order) && defaultOrder)
   			aParams.order = defaultOrder
   		return aParams
	}
	static String makeOrderByClause(params) {
			if(params?.sort && (params?.order && (params.order.equalsIgnoreCase("asc") || params.order.equalsIgnoreCase("desc"))) ) {
				return "order by ${params.sort} ${params.order}"
			} else if(params?.sort) {
				return "order by ${params.sort}"				
			} else {
				return ""
			}
	}
	////
	private PaginateUtils() {}
}