
package com.sdl.odata.processor.write;

import com.sdl.odata.api.ODataBadRequestException;
import com.sdl.odata.api.edm.model.EntityDataModel;
import com.sdl.odata.api.processor.ProcessorResult;
import com.sdl.odata.api.service.ODataRequestContext;
import org.junit.Before;
import org.junit.Test;

import java.io.UnsupportedEncodingException;

import static com.sdl.odata.api.service.ODataRequest.Method.DELETE;
import static com.sdl.odata.api.service.ODataResponse.Status.NO_CONTENT;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.times;

/**
 * The DELETE Method Handler Test.
 */
public class DeleteMethodHandlerTest extends MethodHandlerTest {

    @Before
    public void setup() throws Exception {
        super.setup("Persons");
    }

    private WriteMethodHandler getDeleteMethodHandler(EntityDataModel entityDataModel, boolean isEntitySetUri)
            throws UnsupportedEncodingException {
        ODataRequestContext requestContext = super.createRequestContext(DELETE, isEntitySetUri, entityDataModel);
        return new DeleteMethodHandler(requestContext, dataSourceFactoryMock);
    }

    @Test(expected = ODataBadRequestException.class)
    public void testWriteWithNotNull() throws Exception {
        stubForTesting(getEntity());
        getDeleteMethodHandler(getEntityDataModel(), false).handleWrite(getEntity());
    }


    @Test(expected = ODataBadRequestException.class)
    public void testWriteEntitySet() throws Exception {
        stubForTesting(getEntity());
        getDeleteMethodHandler(getEntityDataModel(), true).handleWrite(getEntity());
    }

    public void doWrite(Object entity, EntityDataModel entityDataModel) throws Exception {
        stubForTesting(entity);
        ProcessorResult result = getDeleteMethodHandler(entityDataModel, false).handleWrite(null);
        assertThat(result.getStatus(), is(NO_CONTENT));
        assertNull(result.getData());
        verify(dataSourceMock, times(1)).delete(entityOdataURI, entityDataModel);
    }

    @Test
    public void testWrite() throws Exception {
        // With ODataPerson
        doWrite(getEntity(), getEntityDataModel());

        // With ODataPersonNamedKey
        doWrite(getEntityForNamedKey(), getEntityDataModelForNamedKey());
    }

}
