package omq.common.util.Serializers;

import omq.exception.SerializerException;

import org.yaml.snakeyaml.Yaml;


/**
 * 
 * @author Sergi Toda <sergi.toda@estudiants.urv.cat>
 * @author Guillermo Guerrero <guillermo.guerrero@estudiants.urv.cat>
 * 
 */
public class YamlImp implements ISerializer {
	private Yaml yaml = new Yaml();
    	
	@Override
	public byte[] serialize(Object obj) throws SerializerException {
		try{
			String output = yaml.dump(obj);			
			return output.getBytes();
		} catch (Exception e){
			throw new SerializerException("Serialize -> " + e.getMessage(), e);
		}
	}
	
	@Override
	public byte[] serialize(Object obj, Class<?> clazz) throws SerializerException {
		return serialize(obj);
	}	

	@Override
	public Object deserialize(byte[] bytes) throws SerializerException {
		try{
			String input = new String(bytes);
			Object obj = yaml.load(input);
			return obj;
		} catch (Exception e){
			throw new SerializerException("Deserialize -> " + e.getMessage(), e);
		}
	}

	@Override
	public Object deserialize(byte[] bytes, Class<?> clazz) throws SerializerException {
		try{
			String input = new String(bytes);
			Object obj = yaml.loadAs(input, clazz);
			return obj;
		} catch (Exception e){
			throw new SerializerException("Deserialize -> " + e.getMessage(), e);
		}
	}
}
