package cn.quant.andy.text;

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

/**
 * Created by Administrator on 2021/7/17 0017.
 */
public class PlaceholderSpiltFormatter extends StringFormatter {

    public final static String FORMATTER_TYPE = "s";

    private String separator;

    public PlaceholderSpiltFormatter(String separator) {
        this.separator = separator;
    }

    Group format(String style, String val) {
        String[] split = val.split(separator);
        Pattern pattern = Pattern.compile("(?<=\\{)\\d*(?=\\})");
        Matcher matcher = pattern.matcher(style);
        int i = 0;
        Group parent = null, group = null;
        while (matcher.find()) {
            int index = index(i++, style, matcher.start(), matcher.end(), split);
            if (group != null) {
                group = group.next = new Group();
            } else {
                group = new Group();
            }
            group.placeholder = matcher.group();
            group.value = split[index];
            if (parent == null) {
                parent = group;
            }
        }
        return parent;
    }

    private int index(int index, String input, int start, int end, String[] split) {
        int s = Math.max(0, start - 1);
        char sc = input.charAt(s);
        if (sc == '{') {
            if (s == 0) {
                return 0;
            }
            if (separator.equals(input.substring(Math.max(0, s - 1), s))) {
                if (input.length() - end == 1) {
                    return Math.max(0, split.length - 1);
                }
            }
        }
        return index;
    }

    public static void main(String[] args) {
        PlaceholderSpiltFormatter formatter = new PlaceholderSpiltFormatter("-");
        Group format = formatter.format("{}-{8}", "dfdwqfwqfew-234324323");
        System.currentTimeMillis();
    }
}
