package com.bares.web.rest;

import com.bares.BaresApp;

import com.bares.domain.Mesa;
import com.bares.domain.Bar;
import com.bares.repository.MesaRepository;
import com.bares.service.MesaService;
import com.bares.service.dto.MesaDTO;
import com.bares.service.mapper.MesaMapper;
import com.bares.web.rest.errors.ExceptionTranslator;
import com.bares.service.dto.MesaCriteria;
import com.bares.service.MesaQueryService;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.web.PageableHandlerMethodArgumentResolver;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import java.util.List;
import java.util.ArrayList;

import static com.bares.web.rest.TestUtil.createFormattingConversionService;
import static org.assertj.core.api.Assertions.assertThat;
import static org.hamcrest.Matchers.hasItem;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;

/**
 * Test class for the MesaResource REST controller.
 *
 * @see MesaResource
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BaresApp.class)
public class MesaResourceIntTest {

    private static final String DEFAULT_NOMBRE = "AAAAAAAAAA";
    private static final String UPDATED_NOMBRE = "BBBBBBBBBB";

    @Autowired
    private MesaRepository mesaRepository;



    @Autowired
    private MesaMapper mesaMapper;
    

    @Autowired
    private MesaService mesaService;

    @Autowired
    private MesaQueryService mesaQueryService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restMesaMockMvc;

    private Mesa mesa;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        final MesaResource mesaResource = new MesaResource(mesaService, mesaQueryService);
        this.restMesaMockMvc = MockMvcBuilders.standaloneSetup(mesaResource)
            .setCustomArgumentResolvers(pageableArgumentResolver)
            .setControllerAdvice(exceptionTranslator)
            .setConversionService(createFormattingConversionService())
            .setMessageConverters(jacksonMessageConverter).build();
    }

    /**
     * Create an entity for this test.
     *
     * This is a static method, as tests for other entities might also need it,
     * if they test an entity which requires the current entity.
     */
    public static Mesa createEntity(EntityManager em) {
        Mesa mesa = new Mesa()
            .nombre(DEFAULT_NOMBRE);
        return mesa;
    }

    @Before
    public void initTest() {
        mesa = createEntity(em);
    }

    @Test
    @Transactional
    public void createMesa() throws Exception {
        int databaseSizeBeforeCreate = mesaRepository.findAll().size();

        // Create the Mesa
        MesaDTO mesaDTO = mesaMapper.toDto(mesa);
        restMesaMockMvc.perform(post("/api/mesas")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(mesaDTO)))
            .andExpect(status().isCreated());

        // Validate the Mesa in the database
        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeCreate + 1);
        Mesa testMesa = mesaList.get(mesaList.size() - 1);
        assertThat(testMesa.getNombre()).isEqualTo(DEFAULT_NOMBRE);
    }

    @Test
    @Transactional
    public void createMesaWithExistingId() throws Exception {
        int databaseSizeBeforeCreate = mesaRepository.findAll().size();

        // Create the Mesa with an existing ID
        mesa.setId(1L);
        MesaDTO mesaDTO = mesaMapper.toDto(mesa);

        // An entity with an existing ID cannot be created, so this API call must fail
        restMesaMockMvc.perform(post("/api/mesas")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(mesaDTO)))
            .andExpect(status().isBadRequest());

        // Validate the Mesa in the database
        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeCreate);
    }

    @Test
    @Transactional
    public void checkNombreIsRequired() throws Exception {
        int databaseSizeBeforeTest = mesaRepository.findAll().size();
        // set the field null
        mesa.setNombre(null);

        // Create the Mesa, which fails.
        MesaDTO mesaDTO = mesaMapper.toDto(mesa);

        restMesaMockMvc.perform(post("/api/mesas")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(mesaDTO)))
            .andExpect(status().isBadRequest());

        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllMesas() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        // Get all the mesaList
        restMesaMockMvc.perform(get("/api/mesas?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(mesa.getId().intValue())))
            .andExpect(jsonPath("$.[*].nombre").value(hasItem(DEFAULT_NOMBRE.toString())));
    }
    

    @Test
    @Transactional
    public void getMesa() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        // Get the mesa
        restMesaMockMvc.perform(get("/api/mesas/{id}", mesa.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.id").value(mesa.getId().intValue()))
            .andExpect(jsonPath("$.nombre").value(DEFAULT_NOMBRE.toString()));
    }

    @Test
    @Transactional
    public void getAllMesasByNombreIsEqualToSomething() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        // Get all the mesaList where nombre equals to DEFAULT_NOMBRE
        defaultMesaShouldBeFound("nombre.equals=" + DEFAULT_NOMBRE);

        // Get all the mesaList where nombre equals to UPDATED_NOMBRE
        defaultMesaShouldNotBeFound("nombre.equals=" + UPDATED_NOMBRE);
    }

    @Test
    @Transactional
    public void getAllMesasByNombreIsInShouldWork() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        // Get all the mesaList where nombre in DEFAULT_NOMBRE or UPDATED_NOMBRE
        defaultMesaShouldBeFound("nombre.in=" + DEFAULT_NOMBRE + "," + UPDATED_NOMBRE);

        // Get all the mesaList where nombre equals to UPDATED_NOMBRE
        defaultMesaShouldNotBeFound("nombre.in=" + UPDATED_NOMBRE);
    }

    @Test
    @Transactional
    public void getAllMesasByNombreIsNullOrNotNull() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        // Get all the mesaList where nombre is not null
        defaultMesaShouldBeFound("nombre.specified=true");

        // Get all the mesaList where nombre is null
        defaultMesaShouldNotBeFound("nombre.specified=false");
    }

    @Test
    @Transactional
    public void getAllMesasByBarIsEqualToSomething() throws Exception {
        // Initialize the database
        Bar bar = BarResourceIntTest.createEntity(em);
        em.persist(bar);
        em.flush();
        mesa.setBar(bar);
        mesaRepository.saveAndFlush(mesa);
        Long barId = bar.getId();

        // Get all the mesaList where bar equals to barId
        defaultMesaShouldBeFound("barId.equals=" + barId);

        // Get all the mesaList where bar equals to barId + 1
        defaultMesaShouldNotBeFound("barId.equals=" + (barId + 1));
    }

    /**
     * Executes the search, and checks that the default entity is returned
     */
    private void defaultMesaShouldBeFound(String filter) throws Exception {
        restMesaMockMvc.perform(get("/api/mesas?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(mesa.getId().intValue())))
            .andExpect(jsonPath("$.[*].nombre").value(hasItem(DEFAULT_NOMBRE.toString())));
    }

    /**
     * Executes the search, and checks that the default entity is not returned
     */
    private void defaultMesaShouldNotBeFound(String filter) throws Exception {
        restMesaMockMvc.perform(get("/api/mesas?sort=id,desc&" + filter))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$").isArray())
            .andExpect(jsonPath("$").isEmpty());
    }


    @Test
    @Transactional
    public void getNonExistingMesa() throws Exception {
        // Get the mesa
        restMesaMockMvc.perform(get("/api/mesas/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateMesa() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        int databaseSizeBeforeUpdate = mesaRepository.findAll().size();

        // Update the mesa
        Mesa updatedMesa = mesaRepository.findById(mesa.getId()).get();
        // Disconnect from session so that the updates on updatedMesa are not directly saved in db
        em.detach(updatedMesa);
        updatedMesa
            .nombre(UPDATED_NOMBRE);
        MesaDTO mesaDTO = mesaMapper.toDto(updatedMesa);

        restMesaMockMvc.perform(put("/api/mesas")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(mesaDTO)))
            .andExpect(status().isOk());

        // Validate the Mesa in the database
        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeUpdate);
        Mesa testMesa = mesaList.get(mesaList.size() - 1);
        assertThat(testMesa.getNombre()).isEqualTo(UPDATED_NOMBRE);
    }

    @Test
    @Transactional
    public void updateNonExistingMesa() throws Exception {
        int databaseSizeBeforeUpdate = mesaRepository.findAll().size();

        // Create the Mesa
        MesaDTO mesaDTO = mesaMapper.toDto(mesa);

        // If the entity doesn't have an ID, it will be created instead of just being updated
        restMesaMockMvc.perform(put("/api/mesas")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(mesaDTO)))
            .andExpect(status().isCreated());

        // Validate the Mesa in the database
        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deleteMesa() throws Exception {
        // Initialize the database
        mesaRepository.saveAndFlush(mesa);

        int databaseSizeBeforeDelete = mesaRepository.findAll().size();

        // Get the mesa
        restMesaMockMvc.perform(delete("/api/mesas/{id}", mesa.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<Mesa> mesaList = mesaRepository.findAll();
        assertThat(mesaList).hasSize(databaseSizeBeforeDelete - 1);
    }

    @Test
    @Transactional
    public void equalsVerifier() throws Exception {
        TestUtil.equalsVerifier(Mesa.class);
        Mesa mesa1 = new Mesa();
        mesa1.setId(1L);
        Mesa mesa2 = new Mesa();
        mesa2.setId(mesa1.getId());
        assertThat(mesa1).isEqualTo(mesa2);
        mesa2.setId(2L);
        assertThat(mesa1).isNotEqualTo(mesa2);
        mesa1.setId(null);
        assertThat(mesa1).isNotEqualTo(mesa2);
    }

    @Test
    @Transactional
    public void dtoEqualsVerifier() throws Exception {
        TestUtil.equalsVerifier(MesaDTO.class);
        MesaDTO mesaDTO1 = new MesaDTO();
        mesaDTO1.setId(1L);
        MesaDTO mesaDTO2 = new MesaDTO();
        assertThat(mesaDTO1).isNotEqualTo(mesaDTO2);
        mesaDTO2.setId(mesaDTO1.getId());
        assertThat(mesaDTO1).isEqualTo(mesaDTO2);
        mesaDTO2.setId(2L);
        assertThat(mesaDTO1).isNotEqualTo(mesaDTO2);
        mesaDTO1.setId(null);
        assertThat(mesaDTO1).isNotEqualTo(mesaDTO2);
    }

    @Test
    @Transactional
    public void testEntityFromId() {
        assertThat(mesaMapper.fromId(42L).getId()).isEqualTo(42);
        assertThat(mesaMapper.fromId(null)).isNull();
    }
}
