/*
 * Copyright 2015 Andrew T. Flowers, K0SM
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package dopplerpsk.util;

import dopplerpsk.Macro;
import java.io.File;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;

/**
 *
 * Class for parsing a macro file from disk.
 * 
 * @author Andrew T. Flowers
 */
public class MacroParser {

    private final File macroDir;

    private Map<String, Macro> macroMap;

    /**
     * Creates a new macro parser.
     * 
     * @param macroDir directory that contains macro files
     */
    public MacroParser(File macroDir) {

        this.macroDir = macroDir;
    }

    /**
     * Loads macros from the macro directory so they can be referenced by the UI.
     */
    public void loadMacros() {
        macroMap = new TreeMap();
        if (!macroDir.exists()) {
            System.out.println("Macro dir does not exist.  No macros will be loaded.");
        } else {
            File[] files = macroDir.listFiles();
           
            for (File f : files) {
                if (f.getName().endsWith(".txt")) {
                    Macro m = parse(f);
                    if (m != null) {
                        macroMap.put(f.getName(), m);
                    }
                }
            }
        }
    }

    /**
     * Gets a macro by name.  Used by UI to get text to send.
     * @param name
     * @return 
     */
    public Macro getMacro(String name) {
        return macroMap.get(name);
    }

    /**
     * returns the map of names to Macros.  Useful for creating a bank
     * of buttons that reference the preset messages.
     * @return 
     */
    public Map<String, Macro> getMacroMap() {
        return macroMap;
    }

    private Macro parse(File macroFile) {
        // read in file as big string
        Macro m = null;
        try {
            String s = FileUtils.readFileToString(macroFile);

            JSONObject obj = new JSONObject(s);

            String text = obj.getString("text");

            m = new Macro(text);
        } catch (Exception e) {
            //If something goes wrong, just dump the exception.
            e.printStackTrace();
        }
        return m;
    }
}
