package com.tofly.feesapi.common.api.impl;

import org.apache.ibatis.parsing.GenericTokenParser;
import org.apache.ibatis.parsing.TokenHandler;

import java.util.Map;

public class MapVariablesParser {

    public static String parse(String string, Map<String, Object> variables) {
        MapVariableTokenHandler handler = new MapVariableTokenHandler(variables);
        GenericTokenParser parser = new GenericTokenParser("{", "}", handler);
        return parser.parse(string);
    }

    private static class MapVariableTokenHandler implements TokenHandler {
        private Map<String, Object> variables;

        public MapVariableTokenHandler(Map<String, Object> variables) {
            this.variables = variables;
        }

        @Override
        public String handleToken(String content) {
            if (variables != null && content != null) {
                content = content.trim();
                if (variables.containsKey(content)) {
                    return variables.get(content).toString();
                }
            }
            return "{" + content + "}";
        }
    }

}