/*
 * Copyright (c) 2011-2020, hubin (jobob@qq.com).
 * <p>
 * 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
 * <p>
 * https://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * 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 cn.com.ty.lift.common.sql;

import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;

import java.lang.reflect.Proxy;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.util.Base64;
import java.util.Collection;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * SqlUtils工具类
 *
 * @author Caratacus
 * @since 2016-11-13
 */
public class SqlUtils {

    private static final SqlFormatter         SQL_FORMATTER             = new SqlFormatter();
    private static final String               h_target                  = "h.target";
    /**
     * MD5
     */
    private static final String               MD5                       = "MD5";
    /**
     * Eight-bit UCS Transformation Format
     */
    public static final  Charset              UTF_8                     = Charset.forName("UTF-8");
    public static final  String               DELEGATE_MAPPED_STATEMENT = "delegate.mappedStatement";
    public static final  String               DELEGATE_BOUND_SQL        = "delegate.boundSql";
    /**
     * 格式sql
     *
     * @param boundSql
     * @param format
     * @return
     */
    public static String sqlFormat(String boundSql, boolean format) {
        if (format) {
            try {
                return SQL_FORMATTER.format(boundSql);
            } catch (Exception ignored) {
            }
        }
        return boundSql;
    }

    public static boolean isNull(Object object){
        return null == object;
    }

    public static boolean isNull(Object... objects){
        if(null == objects || objects.length == 0){
            return true;
        }
        for (Object object : objects) {
            if(null != object){
                return false;
            }
        }
        return true;
    }

    public static boolean notNull(Object object){
        return null != object;
    }

    public static boolean notNull(Object... objects){
        if(null == objects || objects.length == 0){
            return false;
        }
        for (Object object : objects) {
            if(null == object){
                return false;
            }
        }
        return true;
    }
    public static boolean isString(Object object){
        return notNull(object) && (object instanceof String);
    }

    /**
     * 判断字符串是否为空
     *
     * @param cs 需要判断字符串
     * @return 判断结果
     */
    public static boolean isEmpty(final CharSequence cs) {
        if (isNull(cs) || cs.toString().trim().isEmpty()) {
            return true;
        }
        return false;
    }

    /**
     * 判断字符串是否不为空
     *
     * @param cs 需要判断字符串
     * @return 判断结果
     */
    public static boolean notEmpty(final CharSequence cs) {
        return !isEmpty(cs);
    }

    /**
     * 校验集合是否为空
     *
     * @param coll 入参
     * @return boolean
     */
    public static boolean isEmpty(Collection<?> coll) {
        return (coll == null || coll.isEmpty());
    }

    public static boolean notEmpty(Collection<?> coll){
        return !isEmpty(coll);
    }
    /**
     * 判断是不是数字
     * @param cs 输入
     * @return boolean
     */
    public static boolean isNumeric(final CharSequence cs){
        if(isEmpty(cs)){
            return false;
        }
        Pattern pattern = Pattern.compile("[0-9]+");
        Matcher isNum = pattern.matcher(cs);
        return isNum.matches();
    }

    /**
     * 判断是否为boolean类型的字符串
     * @param cs 输入
     * @return boolean
     */
    public static boolean isBoolean(final CharSequence cs){
        if(isEmpty(cs)){
            return false;
        }
        String input = cs.toString().toLowerCase();
        return "true".equals(input) || "false".equals(input);
    }

    /**
     * 获得真正的处理对象,可能多层代理.
     */
    @SuppressWarnings("unchecked")
    public static <T> T realTarget(Object target) {
        if (Proxy.isProxyClass(target.getClass())) {
            MetaObject metaObject = SystemMetaObject.forObject(target);
            return realTarget(metaObject.getValue(h_target));
        }
        return (T) target;
    }

    /**
     * MD5 Base64 加密
     *
     * @param sql 待加密的字符串
     * @return 加密后的字符串
     */
    public static String sqlEncode(String sql) {
        try {
            MessageDigest md5 = MessageDigest.getInstance(MD5);
            //加密后的字符串
            byte[] bytes = md5.digest(sql.getBytes(UTF_8));
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            throw new SqlAnalysisException(e);
        }
    }
    /**
     * 获取当前执行 MappedStatement
     *
     * @param metaObject 元对象
     */
    public static MappedStatement getMappedStatement(MetaObject metaObject) {
        return (MappedStatement) metaObject.getValue(DELEGATE_MAPPED_STATEMENT);
    }

    /**
     * get the bound sql form the MetaObject.
     * @param metaObject MetaObject
     * @return bound sql
     */
    public static BoundSql getBoundSql(MetaObject metaObject) {
        return (BoundSql) metaObject.getValue(DELEGATE_BOUND_SQL);
    }
}
