package com.bares.web.rest;

import com.bares.BaresApp;

import com.bares.domain.Articulo;
import com.bares.domain.ArticuloCategoria;
import com.bares.domain.Bar;
import com.bares.repository.ArticuloRepository;
import com.bares.service.ArticuloService;
import com.bares.service.dto.ArticuloDTO;
import com.bares.service.mapper.ArticuloMapper;
import com.bares.web.rest.errors.ExceptionTranslator;
import com.bares.service.dto.ArticuloCriteria;
import com.bares.service.ArticuloQueryService;

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

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

    private static final Double DEFAULT_PRECIO = 1D;
    private static final Double UPDATED_PRECIO = 2D;

    @Autowired
    private ArticuloRepository articuloRepository;



    @Autowired
    private ArticuloMapper articuloMapper;
    

    @Autowired
    private ArticuloService articuloService;

    @Autowired
    private ArticuloQueryService articuloQueryService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restArticuloMockMvc;

    private Articulo articulo;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        final ArticuloResource articuloResource = new ArticuloResource(articuloService, articuloQueryService);
        this.restArticuloMockMvc = MockMvcBuilders.standaloneSetup(articuloResource)
            .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 Articulo createEntity(EntityManager em) {
        Articulo articulo = new Articulo()
            .nombre(DEFAULT_NOMBRE)
            .precio(DEFAULT_PRECIO);
        return articulo;
    }

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

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

        // Create the Articulo
        ArticuloDTO articuloDTO = articuloMapper.toDto(articulo);
        restArticuloMockMvc.perform(post("/api/articulos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(articuloDTO)))
            .andExpect(status().isCreated());

        // Validate the Articulo in the database
        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeCreate + 1);
        Articulo testArticulo = articuloList.get(articuloList.size() - 1);
        assertThat(testArticulo.getNombre()).isEqualTo(DEFAULT_NOMBRE);
        assertThat(testArticulo.getPrecio()).isEqualTo(DEFAULT_PRECIO);
    }

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

        // Create the Articulo with an existing ID
        articulo.setId(1L);
        ArticuloDTO articuloDTO = articuloMapper.toDto(articulo);

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

        // Validate the Articulo in the database
        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeCreate);
    }

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

        // Create the Articulo, which fails.
        ArticuloDTO articuloDTO = articuloMapper.toDto(articulo);

        restArticuloMockMvc.perform(post("/api/articulos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(articuloDTO)))
            .andExpect(status().isBadRequest());

        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void checkPrecioIsRequired() throws Exception {
        int databaseSizeBeforeTest = articuloRepository.findAll().size();
        // set the field null
        articulo.setPrecio(null);

        // Create the Articulo, which fails.
        ArticuloDTO articuloDTO = articuloMapper.toDto(articulo);

        restArticuloMockMvc.perform(post("/api/articulos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(articuloDTO)))
            .andExpect(status().isBadRequest());

        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllArticulos() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

        // Get all the articuloList
        restArticuloMockMvc.perform(get("/api/articulos?sort=id,desc"))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.[*].id").value(hasItem(articulo.getId().intValue())))
            .andExpect(jsonPath("$.[*].nombre").value(hasItem(DEFAULT_NOMBRE.toString())))
            .andExpect(jsonPath("$.[*].precio").value(hasItem(DEFAULT_PRECIO.doubleValue())));
    }
    

    @Test
    @Transactional
    public void getArticulo() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

        // Get the articulo
        restArticuloMockMvc.perform(get("/api/articulos/{id}", articulo.getId()))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(jsonPath("$.id").value(articulo.getId().intValue()))
            .andExpect(jsonPath("$.nombre").value(DEFAULT_NOMBRE.toString()))
            .andExpect(jsonPath("$.precio").value(DEFAULT_PRECIO.doubleValue()));
    }

    @Test
    @Transactional
    public void getAllArticulosByNombreIsEqualToSomething() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

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

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

    @Test
    @Transactional
    public void getAllArticulosByNombreIsInShouldWork() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

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

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

    @Test
    @Transactional
    public void getAllArticulosByNombreIsNullOrNotNull() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

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

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

    @Test
    @Transactional
    public void getAllArticulosByPrecioIsEqualToSomething() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

        // Get all the articuloList where precio equals to DEFAULT_PRECIO
        defaultArticuloShouldBeFound("precio.equals=" + DEFAULT_PRECIO);

        // Get all the articuloList where precio equals to UPDATED_PRECIO
        defaultArticuloShouldNotBeFound("precio.equals=" + UPDATED_PRECIO);
    }

    @Test
    @Transactional
    public void getAllArticulosByPrecioIsInShouldWork() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

        // Get all the articuloList where precio in DEFAULT_PRECIO or UPDATED_PRECIO
        defaultArticuloShouldBeFound("precio.in=" + DEFAULT_PRECIO + "," + UPDATED_PRECIO);

        // Get all the articuloList where precio equals to UPDATED_PRECIO
        defaultArticuloShouldNotBeFound("precio.in=" + UPDATED_PRECIO);
    }

    @Test
    @Transactional
    public void getAllArticulosByPrecioIsNullOrNotNull() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

        // Get all the articuloList where precio is not null
        defaultArticuloShouldBeFound("precio.specified=true");

        // Get all the articuloList where precio is null
        defaultArticuloShouldNotBeFound("precio.specified=false");
    }

    @Test
    @Transactional
    public void getAllArticulosByCategoriasIsEqualToSomething() throws Exception {
        // Initialize the database
        ArticuloCategoria categorias = ArticuloCategoriaResourceIntTest.createEntity(em);
        em.persist(categorias);
        em.flush();
        articulo.addCategorias(categorias);
        articuloRepository.saveAndFlush(articulo);
        Long categoriasId = categorias.getId();

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

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


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

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

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

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

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

    @Test
    @Transactional
    public void updateArticulo() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

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

        // Update the articulo
        Articulo updatedArticulo = articuloRepository.findById(articulo.getId()).get();
        // Disconnect from session so that the updates on updatedArticulo are not directly saved in db
        em.detach(updatedArticulo);
        updatedArticulo
            .nombre(UPDATED_NOMBRE)
            .precio(UPDATED_PRECIO);
        ArticuloDTO articuloDTO = articuloMapper.toDto(updatedArticulo);

        restArticuloMockMvc.perform(put("/api/articulos")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(articuloDTO)))
            .andExpect(status().isOk());

        // Validate the Articulo in the database
        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeUpdate);
        Articulo testArticulo = articuloList.get(articuloList.size() - 1);
        assertThat(testArticulo.getNombre()).isEqualTo(UPDATED_NOMBRE);
        assertThat(testArticulo.getPrecio()).isEqualTo(UPDATED_PRECIO);
    }

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

        // Create the Articulo
        ArticuloDTO articuloDTO = articuloMapper.toDto(articulo);

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

        // Validate the Articulo in the database
        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deleteArticulo() throws Exception {
        // Initialize the database
        articuloRepository.saveAndFlush(articulo);

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

        // Get the articulo
        restArticuloMockMvc.perform(delete("/api/articulos/{id}", articulo.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<Articulo> articuloList = articuloRepository.findAll();
        assertThat(articuloList).hasSize(databaseSizeBeforeDelete - 1);
    }

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

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

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