/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pw.yumc.Residence.text;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.bukkit.configuration.file.FileConfiguration;

/**
 *
 * @author Administrator
 */
public class Language {
    public Map<String, String> text;

    public Language() {
        text = new HashMap<String, String>();
    }

    public static Language parseText(final FileConfiguration node, final String topkey) {
        final Language newholder = new Language();
        final Set<String> keys = node.getConfigurationSection(topkey).getKeys(false);
        for (final String key : keys) {
            newholder.text.put(key, node.getString(topkey + "." + key));
        }
        return newholder;
    }

    public String getPhrase(final String key) {
        final String[] split = key.split("\\.");
        return getPhrase(split);
    }

    public String getPhrase(final String key, final String words) {
        return this.getPhrase(key.split("\\."), words);
    }

    public String getPhrase(final String[] keys) {
        return this.getPhrase(keys, (String[]) null);
    }

    public String getPhrase(final String[] keys, final String words) {
        if (words == null) {
            return this.getPhrase(keys, (String[]) null);
        }
        return this.getPhrase(keys, words.split("\\."));
    }

    public String getPhrase(final String[] keys, final String[] words) {
        String sentence = "";
        for (final String key : keys) {
            if (sentence.length() == 0) {
                sentence = this.getText(key);
            } else {
                sentence = sentence + " " + this.getText(key).toLowerCase();
            }
        }
        if (words != null) {
            for (int i = 0; i < words.length; i++) {
                sentence = sentence.replaceAll("%" + (i + 1), words[i]);
            }
        }
        return sentence;
    }

    public void setText(final String key, final String intext) {
        text.put(key, intext);
    }

    private String getText(final String key) {
        String t = text.get(key);
        if (t == null) {
            t = "<missing language key: " + key + ">";
        }
        return t;
    }
}
