package org.r3pek.guiatv;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

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

public class ChannelListParser extends DefaultHandler {
	private boolean inName = false;
	private boolean inSigla = false;
	private boolean inType = false;
	private boolean inProvider = false;
	private boolean inProviderName = false;
	
	private Channel currentChannel;
	
	private ArrayList<Channel> result;
	
	public ChannelListParser() {
		result = new ArrayList<Channel>();
	}
	
	private void channelFilter() {
		Set<String> filter = new HashSet<String>(Arrays.asList(
				new String[] {"TIJI", "NASN", "P&A", "ESCAL", "ANIMA", "BLOOE", "RTL", "PRIV", "SPORT TV1 ", "WINE", "CHASS", "DVR", "VIDEO", "CANAL", "CMAGZ", "SportTV", "BBC P", "FMEN",
							  "M POR", "M POP", "M DIS", "M FNK", "M ALT", "M BRA", "M ROM", "M J&B", "M CLS", "M AMB", "M INF", "JUKE", "MAGZ", "TRAIL", "VKIDS", "VMAGZ", "JOGOS", "M NOV",
							  "TVC4"}
				));
		
		if (!filter.contains(currentChannel.getSigla()))
			result.add(currentChannel);
	}
	
	private void checkTag(String tag, boolean newValue) {
		if (tag.equals("GetChannelListResult") && newValue) {
			result.clear();
		} else if (tag.equals("Channel")) {
			if (newValue)
				currentChannel = new Channel();
			else
				channelFilter();
		} else if (tag.equals("Name")) {
			if (!inProvider)
				inName = newValue;
			else
				inProviderName = newValue;
		} else if (tag.equals("Sigla"))
			inSigla = newValue;
		else if (tag.equals("Type"))
			inType = newValue;
		else if (tag.equals("Provider"))
			inProvider = 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));
		
		if (inName)
			currentChannel.setName(currentChannel.getName() + chars);
		else if (inSigla)
			currentChannel.setSigla(currentChannel.getSigla() + chars);
		else if (inType)
			currentChannel.setType(currentChannel.getType() + chars);
		else if (inProviderName)
			currentChannel.setProvider(currentChannel.getProvider() + chars);
	}
	
	public ArrayList<Channel> getChannelList() {
		return result;
	}
	
}
