package com.mobify.astro.messaging;

import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;
import org.skyscreamer.jsonassert.JSONAssert;

import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;

public class RpcRequestTest {

    protected String messageJSON;
    protected RpcRequest testRequest;

    @Before
    public void setup() {
        messageJSON = "{\"method\": \"testMethod\", \"params\": {\"first\": 5, \"second\": \"some string\", \"third\": null}}";
        testRequest = RpcRequestFactory.requestWithPayloadJSON(messageJSON);
    }

    @Test
    public void testGetArgumentsAsObject()
            throws Exceptions.ParametersNotFoundException, JSONException {
        JSONObject expectedArguments = new JSONObject("{\"first\": 5, \"second\": \"some string\", \"third\": null}");
        JSONObject arguments = testRequest.getParameters();

        JSONAssert.assertEquals(expectedArguments, arguments, false);
    }

    @Test
    public void testThrowsArgumentsNotFoundException() {
        RpcRequest req = RpcRequestFactory.requestWithPayloadJSON("{\"method\": \"add\"}");

        try {
            req.getParameters();
            fail();
        } catch (Exceptions.RpcException e) {
            assertEquals(Exceptions.ParametersNotFoundException.class, e.getClass());
        }
    }

    @Test
    public void testGetParameterValues() throws Exception {
        List<Object> values = testRequest.getParameterValues(new String[]{"first", "second", "third"});

        assertEquals(3, values.size());
        assertEquals(5, values.get(0));
        assertEquals("some string", values.get(1));
        // We use `assertSame` because we want to ensure that this is really null and not
        // `JSONObject.NULL`.
        assertSame(null, values.get(2));
    }
}
