package cn.quant.andy.text;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2021/7/19 0019.
 */
public abstract class StringFormatter {

    private final static Map<Object, StringFormatter> formatter = new HashMap<>();

    public static void register(String key, StringFormatter format) {
        if (formatter.containsKey(key)) {
            return;
        }
        formatter.put(key, format);
    }

    abstract Group format(String pattern, String text) throws ParseException;

    public static Group format(Object key, String pattern, String text) throws ParseException {
        StringFormatter formatter = StringFormatter.formatter.get(key);
        if (formatter == null) {
            throw new IllegalArgumentException("No such string formatter." + key);
        }
        return formatter.format(pattern, text);
    }

    public class Group {
        String placeholder;
        Object value;
        Group next = null;

        public String getIndex() {
            return placeholder;
        }

        public Object getValue() {
            return value;
        }

        public <T> T getValue(T t) {
            return (T) value;
        }

        public String getPlaceholder() {
            return placeholder;
        }

        public boolean hasNext() {
            return this.next != null;
        }

        public Group next() {
            return this.next;
        }
    }
}
