/*
 * This file is part of Nuts Framework.
 * Copyright(C) 2009-2012 Nuts Develop Team.
 *
 * Nuts Framework is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License any later version.
 * 
 * Nuts Framework is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with Nuts Framework. If not, see <http://www.gnu.org/licenses/>.
 */
package nuts.exts.struts2.dispatcher;

import nuts.core.bind.json.Jsons;
import nuts.core.lang.Objects;
import nuts.exts.struts2.test.ActionTestCase;
import nuts.exts.struts2.test.TestAction;
import nuts.exts.struts2.test.TestBean;

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

import com.opensymphony.xwork2.ActionProxy;

/**
 * Test {@link JsonResult}
 */
public class JsonResultTest extends ActionTestCase {
	/**
	 * simple test
	 * @throws Exception if an error occurs
	 */
	public void testSimple() throws Exception {

		ActionProxy proxy = createActionProxy("/test", "jsontest");

		assertTrue(proxy.getAction() instanceof TestAction);

		// Get the Action object from the proxy
		TestAction action = (TestAction) proxy.getAction();

		TestBean bean = action.getBean();
		if (bean == null) {
			bean = new TestBean();
			bean.setTestData();
			action.setBean(bean);
		}

		bean.setSelf(bean);

		bean.setByteArray(new byte[10]);
		bean.setStrArray(new String[] { "a", "a", "\"", "\\", "/", "\b", "\f", "\n", "\r", "\t" });

		List<Object> list = new ArrayList<Object>();
		list.add("b");
		list.add(1);
		list.add(new int[] { 10, 12 });
		bean.setList(list);

		//keep order in map
		Map<String, Object> map = new LinkedHashMap<String, Object>();
		map.put("a", 1);
		map.put("c", new float[] { 1.0f, 2.0f });
		bean.setMap(map);

		// Run the Struts Interceptor stack and the Action
		String result = proxy.execute();

		// Check the results
		assertEquals(TestAction.SUCCESS, result);

		String rc = getResponseContentAsString();

		Map rjo = Jsons.fromJson(rc, HashMap.class);
		assertEquals(Boolean.TRUE, rjo.get("success"));

		TestBean rtb = Objects.cast(rjo.get("bean"), TestBean.class);

		assertEquals(rtb.getBooleanField(), bean.getBooleanField());
		assertEquals(rtb.getByteField(), bean.getByteField());
		assertEquals(rtb.getCharField(), bean.getCharField());
		assertEquals(rtb.getIntField(), bean.getIntField());
		assertEquals(rtb.getLongField(), bean.getLongField());
		assertEquals(rtb.getFloatField(), bean.getFloatField(), 1);
		assertEquals(rtb.getDoubleField(), bean.getDoubleField(), 1);
		assertEquals(rtb.getDateField(), bean.getDateField());
	}
}
