package jp.sf.amateras.cookiesession.util;

import java.util.HashMap;
import java.util.Map;

import jp.sf.amateras.cookiesession.cipher.Cipher;
import jp.sf.amateras.cookiesession.exception.CookieSessionException;
import net.arnx.jsonic.JSON;

/**
 *
 * @author Naoki Takezoe
 */
public class CookieSessionUtil {

	public static String encode(Cipher chiper, Map<String, Object> attributes){
		Map<String, Map<String, String>> map = new HashMap<String, Map<String,String>>();

		for(Map.Entry<String, Object> entry: attributes.entrySet()){
			String name = entry.getKey();
			Object value = entry.getValue();

			Map<String, String> info = new HashMap<String, String>();
			info.put("type", value.getClass().getName());
//			info.put("json", JSON.encode(value).replaceAll("\"", "\\\\\""));
			info.put("json", JSON.encode(value));

			map.put(name, info);
		}

		String json = JSON.encode(map);
		String encodedValue = chiper.encrypt(json);

		return encodedValue;
	}

	public static Map<String, Object> decode(Cipher chiper, String cookie){
		String decodedValue = chiper.decrypt(cookie);

		@SuppressWarnings("unchecked")
		Map<String, Map<String, String>> map = (Map<String, Map<String, String>>) JSON.decode(decodedValue);
		Map<String, Object> attributes = new HashMap<String, Object>();
		for(Map.Entry<String, Map<String, String>> entry: map.entrySet()){
			String name = entry.getKey();
			Map<String, String> info = entry.getValue();
			String type = info.get("type");
			String json = info.get("json");

			try {
				Object value = JSON.decode(json, Class.forName(type));
				attributes.put(name, value);

			} catch(ClassNotFoundException ex){
				throw new CookieSessionException(ex);
			}
		}

		return attributes;
	}

}
