package com.mobify.astro.plugins;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.test.InstrumentationRegistry;
import android.widget.SearchView;

import com.mobify.astro.ActivityTestBase;
import com.mobify.astro.PluginResolver;
import com.mobify.astro.messaging.EventManager;
import com.mobify.astro.messaging.MessageSender;

import org.json.JSONObject;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class SearchBarPluginTest extends ActivityTestBase {

    private SearchBarPlugin searchBarPlugin;
    private EventManager mockEventManager;

    @Before
    public void setup() throws Throwable {
        mockEventManager = mock(EventManager.class);
    }

    private void initSearchBarPlugin() {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                PluginResolver mockPluginResolver = mock(PluginResolver.class);
                MessageSender messageSender = new MessageSender(mockEventManager);
                searchBarPlugin = new SearchBarPlugin(getActivity(), mockPluginResolver, mockEventManager, messageSender);

            }
        });
        InstrumentationRegistry.getInstrumentation().waitForIdleSync();
    }

    private SearchView getSearchBarView() {
        return (SearchView) searchBarPlugin.getView();
    }

    @Test
    public void testGetView() {
        initSearchBarPlugin();
        assertNotNull(getSearchBarView());
    }

    @Test
    public void testSetQuery() {
        initSearchBarPlugin();
        String test = "apples";
        searchBarPlugin.setQuery(test);
        assertEquals(getSearchBarView().getQuery().toString(), test);
    }

    @Test
    public void testSetPlaceholderText() {
        initSearchBarPlugin();
        String test = "incredible";
        searchBarPlugin.setPlaceholderText(test);
        assertEquals(getSearchBarView().getQueryHint(), test);
    }

    @Test
    public void testSetBackgroundColor() {
        initSearchBarPlugin();
        String blue = "#0000FF";
        searchBarPlugin.setBackgroundColor(blue);
        assertEquals(((ColorDrawable) getSearchBarView().getBackground()).getColor(), Color.parseColor(blue));
    }

    @Test
    public void testSubmit() {
        initSearchBarPlugin();
        final String test = "oranges";
        searchBarPlugin.setQuery(test);
        searchBarPlugin.submit();
        String address = searchBarPlugin.getEventsAddress();
        verify(mockEventManager, times(3)).trigger(eq(address), any(JSONObject.class));
    }
}
