package com.community.commom.utils;

import org.springframework.util.StringUtils;

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

/**
 * 类名称：com.yincheng.jcjy.huiju.common.utils
 * 类描述：日常工具类
 * 创建人：Geng Xiang
 * 创建时间：2017/11/8 14:29
 *
 * @version 1.0.0
 */
public class CommonUtils {

    public static Integer str2Int(String target) {
        if (target != null && target.trim().length() > 0) {
            return Integer.parseInt(target);
        }
        return null;
    }

    public static boolean patterMatch(String target, String patternStr) {
        Pattern pattern = Pattern.compile(patternStr);          // ""
        Matcher matcher = pattern.matcher(target);
        return matcher.matches();
    }


    /**
     * 正则匹配获取参数
     * 目前只取一个
     *
     * @param target 目标String
     * @param parn   匹配表达式
     * @return List<String>
     */
    public static List<String> formatParam(String target, String prefix, String parn) {
        List<String> result = new ArrayList<>();
        Pattern p = Pattern.compile(parn);
        Matcher m = p.matcher(target);
        while (m.find()) {
            if (StringUtils.hasText(prefix)){
                result.add(m.group().substring(prefix.length()));
            } else{
                result.add(m.group());
            }
        }

        if (result == null || result.size() == 0){
            result.add("");
        }
        return result;
    }

    /**
     * 正则匹配获取参数 删除已匹配数据
     * 目前只取一个
     *
     * @param target 目标String
     * @param parn   匹配表达式
     * @return List<String>
     */
    public static List<String> formatParam(StringBuffer target, String prefix, String parn) {
        List<String> result = new ArrayList<>();
        String targetStr = target.toString();
        Pattern p = Pattern.compile(parn);
        Matcher m = p.matcher(targetStr);
        while (m.find()) {
            if (StringUtils.hasText(prefix)){
                result.add(m.group().substring(prefix.length()));
            } else{
                result.add(m.group());
            }
            //删除已匹配的参数
            target.delete(target.indexOf(m.group()), target.indexOf(m.group())+m.group().length());
        }

        if (result == null || result.size() == 0){
            result.add("");
        }
        return result;
    }
}
