package net.yyc.common.rabbitmq.core;

import net.yyc.common.core.entity.BaseMap;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;

import java.util.Base64;
import java.util.List;

public class JavaSerializationMessageConverterTest {

	private static final String PRODUCTION_PAYLOAD_BASE64 =
			"rO0ABXNyAC9jb20ucXVuemhpeGlueGkuaG5xei5jb21tb24uY29yZS5lbnRpdHkuQmFzZU1hcLxcUd0p4zDnAgAAeHIAEWphdmEudXRpbC5IYXNoTWFwBQfa\n" +
					"wcMWYNEDAAJGAApsb2FkRmFjdG9ySQAJdGhyZXNob2xkeHA/QAAAAAAADHcIAAAAEAAAAAJ0AAd0YXNrSWRzc3IAEWphdmEudXRpbC5Db2xsU2VyV46rtjob\n" +
					"qBEDAAFJAAN0YWd4cAAAAAF3BAAAAAF0AAczNzc2MzE4eHQABnN0YXR1c3QAATN4";

	@Test
	public void fromMessage_shouldDeserializeProductionPayload() {
		JavaSerializationMessageConverter converter = new JavaSerializationMessageConverter();
		byte[] body = Base64.getDecoder().decode(PRODUCTION_PAYLOAD_BASE64.replace("\n", "").replace("\r", ""));
		Message message = new Message(body, new MessageProperties());

		Object result = converter.fromMessage(message);

		Assert.assertTrue(result instanceof BaseMap);
		BaseMap baseMap = (BaseMap) result;
		Assert.assertEquals("3", baseMap.get("status"));

		List<Long> taskIds = baseMap.getListLong("taskIds");
		Assert.assertNotNull(taskIds);
		Assert.assertEquals(1, taskIds.size());
		Assert.assertEquals(Long.valueOf(3776318L), taskIds.get(0));
	}

	@Test
	public void toMessage_shouldSerializeAsLegacyBaseMap() {
		JavaSerializationMessageConverter converter = new JavaSerializationMessageConverter();
		BaseMap baseMap = new BaseMap();
		baseMap.put("taskIds", java.util.Collections.singletonList("3776318"));
		baseMap.put("status", "3");

		Message message = converter.toMessage(baseMap, new MessageProperties());

		Assert.assertNotNull(message.getBody());
		Assert.assertTrue(message.getBody().length > 2);
		Assert.assertEquals((byte) 0xAC, message.getBody()[0]);
		Assert.assertEquals((byte) 0xED, message.getBody()[1]);

		BaseMap roundTrip = (BaseMap) converter.fromMessage(message);
		Assert.assertEquals("3", roundTrip.get("status"));
	}
}
