package org.beetl.core.aa;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.beetl.core.BasicTestCase;
import org.beetl.core.Template;
import org.beetl.core.om.AABuilder;
import org.beetl.core.om.AsmAAFactory;
import org.beetl.core.om.AttributeAccess;
import org.beetl.core.resource.StringTemplateResourceLoader;
import org.testng.annotations.Test;

public class JacksonTest extends BasicTestCase {
	@Test
	public void test() throws Exception {
		AABuilder aaBuilder = gt.getAttributeAccessFactory();
		aaBuilder.defaultAAFactory = new MyAttributeFactory();

		ObjectMapper objectMapper = new ObjectMapper();
		JsonNode node = objectMapper.readTree("{\"attr\":[1,2]}");

		Template t = gt.getTemplate("${a.attr[1]}",new StringTemplateResourceLoader());
		t.binding("a",node);
		String ret = t.render();
		System.out.println(ret);

	}
	public static class  MyAttributeFactory extends AsmAAFactory {
		public MyAttributeFactory(){
			super();
			classAttrs.put(ArrayNode.class, new JacksonArrayNode() );
			classAttrs.put(ObjectNode.class, new JacksonObjectNode() );
		}

	}

	public static class JacksonArrayNode extends AttributeAccess {

		@Override
		public Object value(Object o, Object attr) {
			ArrayNode arrayNode = (ArrayNode)o;
			int index = ((Number)attr).intValue();
			return arrayNode.get(index);
		}

	}

	public static class JacksonObjectNode extends AttributeAccess {

		@Override
		public Object value(Object o, Object attr) {
			ObjectNode objectNode = (ObjectNode)o;
			String attrName = attr.toString();
			return objectNode.get(attrName);
		}

	}
}
