/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.ag.ui.ws.rs.operation.voting;

import com.google.gson.JsonObject;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.junit.contrib.java.lang.system.RestoreSystemProperties;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.slf4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.Response;

import com.scytl.products.ov.ag.services.infrastructure.remote.voting.VotingWorkflowVotingClient;
import com.scytl.products.ov.ag.ui.ws.rs.RestApplication;
import com.scytl.products.ov.ag.ui.ws.rs.proxy.XForwardedForFactoryImpl;
import com.scytl.products.ov.commons.tracking.TrackIdGenerator;

import retrofit2.Call;

import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.when;

import java.io.IOException;

public class CastCodeResourceTest extends JerseyTest {

    private static final String VERSION = "1v";

    private static final String ELECTION_EVENT_ID = "1e";

    private static final String AUTH_TOKEN = "authToken";

    private static final String TRACK_ID = "trackId";

    private static final String TENANT_ID = "100t";
    
    private static final String VOTING_CARD_ID = "1vc";

    private static final String X_FORWARDER_VALUE = "localhost,";

    public static final String URL_CAST_CODE_CONTEXT_DATA = CastCodeResource.RESOURCE_PATH;

    @Rule
    public TestRule restoreSystemProperties = new RestoreSystemProperties();

    @Mock
    Logger logger;
    
    @Mock
    TrackIdGenerator trackIdGenerator;

    @Mock
    HttpServletRequest servletRequest;

    @Mock
    VotingWorkflowVotingClient votingWorkflowVotingClient;

    CastCodeResource sut;

    @Test
    public void getStatusOfVotingCards() throws IOException {

        int mockedInvocationStatus = 200;
        commonPreparation();
        JsonObject reply = new JsonObject();
        reply.addProperty("castCodes", "areHere");
        
        @SuppressWarnings("unchecked")
		Call<JsonObject> callMock = (Call<JsonObject>) Mockito.mock(Call.class);
        when(callMock.execute()).thenReturn(retrofit2.Response.success(reply));
        
        when(votingWorkflowVotingClient.getCastCodeMessage(eq(CastCodeResource.CAST_CODE_PATH), eq(TENANT_ID), eq(ELECTION_EVENT_ID),
            eq(VOTING_CARD_ID), eq(AUTH_TOKEN), eq(X_FORWARDER_VALUE), eq(TRACK_ID)))
                .thenReturn(callMock);

        Response response = target(URL_CAST_CODE_CONTEXT_DATA)
                .resolveTemplate("tenantId", TENANT_ID)
                .resolveTemplate("electionEventId", ELECTION_EVENT_ID)
                .resolveTemplate("version", VERSION)
                .resolveTemplate("votingCardId", VOTING_CARD_ID)
                .request()
                .header(RestApplication.PARAMETER_AUTHENTICATION_TOKEN, AUTH_TOKEN)
                .get();
        int status = response.getStatus();

        Assert.assertEquals(mockedInvocationStatus, status);
        Assert.assertEquals(reply.toString(), response.readEntity(String.class));
    }

    private void commonPreparation() {
        when(servletRequest.getHeader(eq(XForwardedForFactoryImpl.HEADER))).thenReturn("localhost");
        when(servletRequest.getHeader(eq(RestApplication.PARAMETER_AUTHENTICATION_TOKEN))).thenReturn(AUTH_TOKEN);
        
        when(servletRequest.getRemoteAddr()).thenReturn("");
        when(servletRequest.getLocalAddr()).thenReturn("");
        when(trackIdGenerator.generate()).thenReturn(TRACK_ID);
    }

    @Override
    protected Application configure() {

        System.setProperty("VOTING_WORKFLOW_CONTEXT_URL", "localhost");
        MockitoAnnotations.initMocks(this);

        AbstractBinder binder = new AbstractBinder() {
            @Override
            protected void configure() {
            	bind(logger).to(Logger.class);
                bind(servletRequest).to(HttpServletRequest.class);
            }
        };
        sut = new CastCodeResource(votingWorkflowVotingClient, trackIdGenerator);
        forceSet(TestProperties.CONTAINER_PORT, "0");
        return new ResourceConfig().register(sut).register(binder);
    }
}
