package org.jerrymouse.cc.site.convert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jerrymouse.cc.site.bean.Format;
import org.jerrymouse.cc.site.bean.Resource;
import org.jerrymouse.cc.site.bean.Type;
import org.jerrymouse.cc.site.convert.image.ImageConvertor;
import org.jerrymouse.cc.site.convert.image.SvgConvertor;
import org.jerrymouse.cc.site.convert.video.To3gpConvertor;
import org.jerrymouse.cc.site.convert.video.ToOgvConvertor;

public class CommonConvertor implements Convertor {

	private static List<Convertor> convertors;

	static {
		convertors = new ArrayList<Convertor>();
		convertors.add(new ImageConvertor());
		convertors.add(new SvgConvertor());
		convertors.add(new To3gpConvertor());
		convertors.add(new ToOgvConvertor());
	}

	public byte[] convert(Resource resource) throws UnSuportTypeException {
		if (resource.getFormat() == null) {
			resource.setFormat(new Format(resource.getOrgType()));
		}
		if (resource.getOrgType().equals(resource.getFormat().getType())) {
			return resource.getOrgBytes();
		}
		Convertor convertor = buildConvertor(resource.getOrgType(), resource
				.getFormat().getType());
		return convertor.convert(resource);
	}

	private Convertor buildConvertor(Type from, Type to)
			throws UnSuportTypeException {
		for (Convertor convertor : convertors) {
			List<Type> l = convertor.support().get(from);
			if (l != null && l.contains(to)) {
				return convertor;
			}
		}
		throw new UnSuportTypeException();
	}

	public Map<Type, List<Type>> support() {
		Map<Type, List<Type>> map = new HashMap<Type, List<Type>>();
		for (Convertor convertor : convertors) {
			map.putAll(convertor.support());
		}
		return map;
	}

}
