/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.common.utils;

import com.crunii.micro.common.constants.DSConstants;
import com.crunii.micro.common.dto.PageReq;
import com.crunii.micro.common.exception.BusinessException;

import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 田平 create 2016年4月13日下午5:36:03
 */
public class SqlUtil {
	private static final Pattern dbName = Pattern.compile("pf_conf:|pf_prod:|pf_his:|proj_new97:|emos_intf:|rpt:");

	public static String getInformixEscapeSql(String sql) {
		StringBuffer sbsql = new StringBuffer(sql);
		Matcher m = dbName.matcher(sql);
		int i = 0;
		while (m.find()) {
			sbsql.insert(m.end() - 1 + i, "\\");
			++i;
		}
		return sbsql.toString();
	}

	public static boolean appendAnd(StringBuilder sb, boolean appendAnd) {
		if (appendAnd == false) {
			sb.append(" where ");
		} else {
			sb.append(" and ");
		}
		return true;
	}

	public static String appendIn(int size) {
		StringBuilder sb = new StringBuilder();
		java.lang.String result = "";
		for (int i = 0; i < size; i++) {
			sb.append("?,");
		}
		result = sb.toString().substring(0, sb.toString().length() - 1);
		return result;
	}

	public static void appendLimit(String dbType, List<Object> params, StringBuilder sb, PageReq<?> req) {
		if (DSConstants.DATABASE_MYSQL.equalsIgnoreCase(dbType)) {
			sb.append(" limit ?,? ");
			params.add(req.getMyStart());
			params.add(req.getPageSize());
		} else if (DSConstants.DATABASE_POSTGRESQL.equalsIgnoreCase(dbType)) {
			sb.append(" limit ? offset ? ");
			params.add(req.getPageSize());
			params.add(req.getMyStart());
		} else {
			throw new BusinessException("unsupported this dbType:{}!", dbType);
		}
	}

	public static void appendLimit(String dbType, Map<String,Object> params, StringBuilder sb, PageReq<?> req) {
		if (DSConstants.DATABASE_MYSQL.equalsIgnoreCase(dbType)) {
			sb.append(" limit :limit,:offset ");
			params.put("limit",req.getMyStart());
			params.put("offset",req.getPageSize());
		} else if (DSConstants.DATABASE_POSTGRESQL.equalsIgnoreCase(dbType)) {
			sb.append(" limit :limit offset :offset ");
			params.put("limit",req.getPageSize());
			params.put("offset",req.getMyStart());
		} else {
			throw new BusinessException("unsupported this dbType:{}!", dbType);
		}
	}

}
