package org.r3pek.guiatv;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

import android.util.Log;

public class ProgramListParser extends DefaultHandler {
	private boolean inTile = false;
	private boolean inDesc = false;
	private boolean inStartTime = false;
	private boolean inEndTime = false;
	private boolean inDuration = false;
	
	private Program currentProgram;
	
	private ArrayList<Program> result;
	
	public ProgramListParser() {
		result = new ArrayList<Program>();
	}
	
	private void checkTag(String tag, boolean newValue) {
		if (tag.equals("GetChannelByDateIntervalResult") && newValue) {
			result.clear();
		} else if (tag.equals("Program")) {
			if (newValue)
				currentProgram = new Program();
			else 
				result.add(currentProgram);
		} else if (tag.equals("Title"))
				inTile = newValue;
		else if (tag.equals("Description"))
			inDesc = newValue;
		else if (tag.equals("StartTime"))
			inStartTime = newValue;
		else if (tag.equals("EndTime"))
			inEndTime = newValue;
		else if (tag.equals("Duration"))
			inDuration = newValue;
	}
	
	public void startElement(String uri, String name, String qName, Attributes atts) {
		checkTag(name.trim(), true);
	}

	public void endElement(String uri, String name, String qName) {
		checkTag(name.trim(), false);
	}
	
	public void characters(char ch[], int start, int length) {
		String chars = (new String(ch).substring(start, start + length));
		
		try {
			if (inTile)
				currentProgram.setTitle(currentProgram.getTitle() + chars);
			else if (inDesc)
				currentProgram.setDescription(currentProgram.getDescription() + chars);
			else if (inStartTime)
				currentProgram.setStartHour(currentProgram.getStartHour() + chars);
			else if (inEndTime)
				currentProgram.setEndHour(currentProgram.getEndHour() + chars);
			else if (inDuration)
				currentProgram.setDurantion(Integer.parseInt(chars));
		} catch (Exception e) { Log.d("ProgramParse", e.getMessage()); }
	}
	
	public ArrayList<Program> getProgramList() {
		return result;
	}
	
}
