package com.bares.web.rest;

import com.bares.BaresApp;

import com.bares.domain.Bar;
import com.bares.domain.Producto;
import com.bares.domain.Categoria;
import com.bares.domain.Articulo;
import com.bares.domain.User;
import com.bares.repository.BarRepository;
import com.bares.service.BarService;
import com.bares.service.dto.BarDTO;
import com.bares.service.mapper.BarMapper;
import com.bares.web.rest.errors.ExceptionTranslator;
import com.bares.service.dto.BarCriteria;
import com.bares.service.BarQueryService;

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 BarResource REST controller.
 *
 * @see BarResource
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = BaresApp.class)
public class BarResourceIntTest {

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

    @Autowired
    private BarRepository barRepository;



    @Autowired
    private BarMapper barMapper;
    

    @Autowired
    private BarService barService;

    @Autowired
    private BarQueryService barQueryService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restBarMockMvc;

    private Bar bar;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        final BarResource barResource = new BarResource(barService, barQueryService);
        this.restBarMockMvc = MockMvcBuilders.standaloneSetup(barResource)
            .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 Bar createEntity(EntityManager em) {
        Bar bar = new Bar()
            .nombre(DEFAULT_NOMBRE);
        // Add required entity
        Producto productos = ProductoResourceIntTest.createEntity(em);
        em.persist(productos);
        em.flush();
        bar.getProductos().add(productos);
        // Add required entity
        Categoria categorias = CategoriaResourceIntTest.createEntity(em);
        em.persist(categorias);
        em.flush();
        bar.getCategorias().add(categorias);
        // Add required entity
        Articulo articulos = ArticuloResourceIntTest.createEntity(em);
        em.persist(articulos);
        em.flush();
        bar.getArticulos().add(articulos);
        return bar;
    }

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

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

        // Create the Bar
        BarDTO barDTO = barMapper.toDto(bar);
        restBarMockMvc.perform(post("/api/bars")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(barDTO)))
            .andExpect(status().isCreated());

        // Validate the Bar in the database
        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeCreate + 1);
        Bar testBar = barList.get(barList.size() - 1);
        assertThat(testBar.getNombre()).isEqualTo(DEFAULT_NOMBRE);
    }

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

        // Create the Bar with an existing ID
        bar.setId(1L);
        BarDTO barDTO = barMapper.toDto(bar);

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

        // Validate the Bar in the database
        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeCreate);
    }

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

        // Create the Bar, which fails.
        BarDTO barDTO = barMapper.toDto(bar);

        restBarMockMvc.perform(post("/api/bars")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(barDTO)))
            .andExpect(status().isBadRequest());

        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllBars() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

    @Test
    @Transactional
    public void getBar() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

    @Test
    @Transactional
    public void getAllBarsByNombreIsEqualToSomething() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

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

    @Test
    @Transactional
    public void getAllBarsByNombreIsInShouldWork() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

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

    @Test
    @Transactional
    public void getAllBarsByNombreIsNullOrNotNull() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

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

    @Test
    @Transactional
    public void getAllBarsByProductosIsEqualToSomething() throws Exception {
        // Initialize the database
        Producto productos = ProductoResourceIntTest.createEntity(em);
        em.persist(productos);
        em.flush();
        bar.addProductos(productos);
        barRepository.saveAndFlush(bar);
        Long productosId = productos.getId();

        // Get all the barList where productos equals to productosId
        defaultBarShouldBeFound("productosId.equals=" + productosId);

        // Get all the barList where productos equals to productosId + 1
        defaultBarShouldNotBeFound("productosId.equals=" + (productosId + 1));
    }


    @Test
    @Transactional
    public void getAllBarsByCategoriasIsEqualToSomething() throws Exception {
        // Initialize the database
        Categoria categorias = CategoriaResourceIntTest.createEntity(em);
        em.persist(categorias);
        em.flush();
        bar.addCategorias(categorias);
        barRepository.saveAndFlush(bar);
        Long categoriasId = categorias.getId();

        // Get all the barList where categorias equals to categoriasId
        defaultBarShouldBeFound("categoriasId.equals=" + categoriasId);

        // Get all the barList where categorias equals to categoriasId + 1
        defaultBarShouldNotBeFound("categoriasId.equals=" + (categoriasId + 1));
    }


    @Test
    @Transactional
    public void getAllBarsByArticulosIsEqualToSomething() throws Exception {
        // Initialize the database
        Articulo articulos = ArticuloResourceIntTest.createEntity(em);
        em.persist(articulos);
        em.flush();
        bar.addArticulos(articulos);
        barRepository.saveAndFlush(bar);
        Long articulosId = articulos.getId();

        // Get all the barList where articulos equals to articulosId
        defaultBarShouldBeFound("articulosId.equals=" + articulosId);

        // Get all the barList where articulos equals to articulosId + 1
        defaultBarShouldNotBeFound("articulosId.equals=" + (articulosId + 1));
    }


    @Test
    @Transactional
    public void getAllBarsByPropietarioIsEqualToSomething() throws Exception {
        // Initialize the database
        User propietario = UserResourceIntTest.createEntity(em);
        em.persist(propietario);
        em.flush();
        bar.setPropietario(propietario);
        barRepository.saveAndFlush(bar);
        Long propietarioId = propietario.getId();

        // Get all the barList where propietario equals to propietarioId
        defaultBarShouldBeFound("propietarioId.equals=" + propietarioId);

        // Get all the barList where propietario equals to propietarioId + 1
        defaultBarShouldNotBeFound("propietarioId.equals=" + (propietarioId + 1));
    }

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

    /**
     * Executes the search, and checks that the default entity is not returned
     */
    private void defaultBarShouldNotBeFound(String filter) throws Exception {
        restBarMockMvc.perform(get("/api/bars?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 getNonExistingBar() throws Exception {
        // Get the bar
        restBarMockMvc.perform(get("/api/bars/{id}", Long.MAX_VALUE))
            .andExpect(status().isNotFound());
    }

    @Test
    @Transactional
    public void updateBar() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

        // Update the bar
        Bar updatedBar = barRepository.findById(bar.getId()).get();
        // Disconnect from session so that the updates on updatedBar are not directly saved in db
        em.detach(updatedBar);
        updatedBar
            .nombre(UPDATED_NOMBRE);
        BarDTO barDTO = barMapper.toDto(updatedBar);

        restBarMockMvc.perform(put("/api/bars")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(barDTO)))
            .andExpect(status().isOk());

        // Validate the Bar in the database
        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeUpdate);
        Bar testBar = barList.get(barList.size() - 1);
        assertThat(testBar.getNombre()).isEqualTo(UPDATED_NOMBRE);
    }

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

        // Create the Bar
        BarDTO barDTO = barMapper.toDto(bar);

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

        // Validate the Bar in the database
        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deleteBar() throws Exception {
        // Initialize the database
        barRepository.saveAndFlush(bar);

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

        // Get the bar
        restBarMockMvc.perform(delete("/api/bars/{id}", bar.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<Bar> barList = barRepository.findAll();
        assertThat(barList).hasSize(databaseSizeBeforeDelete - 1);
    }

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

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

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