package metalexer.jflex;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import junit.framework.TestCase;

public class MetaScannerPropHelper extends TestCase {
    private static final String RESTORE_EMBEDDING_NAME = "<<RESTORE>>";

    private final String layoutName;

    private final String baseDir;
    private final String outDir;

    private Properties macroProp;
    private Properties embeddingProp;
    private Map<Integer, String> embeddingMap;

    protected MetaScannerPropHelper(String groupName, String layoutName) {
        this.layoutName = layoutName;
        this.baseDir = "test/backend-jflex";
        this.outDir = baseDir + "/out/" + groupName + "/" + layoutName;
    }

    private static Properties loadPropFile(String outDir, String filename, String failMsg) {
        try {
            Properties prop = new Properties();
            prop.load(new FileInputStream(outDir + "/" + filename));
            return prop;
        } catch(IOException e) {
            throw new RuntimeException(failMsg, e);
        }
    }

    private Properties getMacroProp() {
        if(macroProp == null) {
            macroProp = loadPropFile(outDir, layoutName + Constants.MACRO_PROP_FILE_EXT, "Failed to load macro properties");
        }
        return macroProp;
    }

    private Properties getEmbeddingProp() {
        if(embeddingProp == null) {
            embeddingProp = loadPropFile(outDir, layoutName + Constants.EMBEDDING_PROP_FILE_EXT, "Failed to load embedding properties");
            embeddingMap = new HashMap<Integer, String>();
            for(Map.Entry<Object, Object> entry : embeddingProp.entrySet()) {
                embeddingMap.put(Integer.parseInt((String) entry.getValue()), (String) entry.getKey());
            }
        }
        return embeddingProp;
    }

    public char getMacroValue(String name) {
        return ((String) getMacroProp().get(name)).charAt(0);
    }

    public int getEmbeddingValue(String name) {
        return RESTORE_EMBEDDING_NAME.equals(name) ? -1 : Integer.parseInt((String) getEmbeddingProp().get(name));
    }

    public String getEmbeddingName(int val) {
        return (val < 0) ? RESTORE_EMBEDDING_NAME : embeddingMap.get(val);
    }
}
