package org.positrium.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.positrium.ui.FileResource;

public class BBMenuParser {
	private File menuResource = null;
	private List<BBCommand> commands = new ArrayList<BBCommand>();

	public BBMenuParser(String menuPath) {

		try {
			menuResource = new File(new FileResource(menuPath).toPath());

		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}
	}

	public void parse() {
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(menuResource));
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		}

		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				// TASK: reqExpでパターン抽出した方が得
				String[] tokens = line.split("\t");

				if (tokens.length>1 && tokens[1].startsWith("[")) {
					BBCommand comm = new BBCommand();
					String cmd = this.stripBlacket(tokens[1]).toLowerCase();
					
					if ("exec".equals(cmd)) {
						comm.tag = BBCommand.Tag.EXEC;
						comm.label = this.stripBlacket(tokens[2]);
						comm.target = this.stripBlacket(tokens[3]);
						
					}else if("quit".equals(cmd)){
						comm.tag = BBCommand.Tag.QUIT;
						comm.label = this.stripBlacket(tokens[2]);
						
					}else if("separator".equals(cmd)){
						comm.tag = BBCommand.Tag.SEPARATOR;
						
					}
					
					this.commands.add(comm);
				}
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	public List<BBCommand> getCommands() {
		this.parse();
		return this.commands;
	}

	private String stripBlacket(String in) {
		String t_in = 
			in.replace("[","")
			.replace("]","")
			.replace("(","")
			.replace(")","")
			.replace("{","")
			.replace("}","")
			.replaceAll("\"", "");
		return t_in;
	}

}
