package com.bares.web.rest;

import com.bares.BaresApp;

import com.bares.domain.Propietario;
import com.bares.domain.User;
import com.bares.repository.PropietarioRepository;
import com.bares.service.PropietarioService;
import com.bares.service.dto.PropietarioDTO;
import com.bares.service.mapper.PropietarioMapper;
import com.bares.web.rest.errors.ExceptionTranslator;
import com.bares.service.dto.PropietarioCriteria;
import com.bares.service.PropietarioQueryService;

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

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

    @Autowired
    private PropietarioRepository propietarioRepository;



    @Autowired
    private PropietarioMapper propietarioMapper;
    

    @Autowired
    private PropietarioService propietarioService;

    @Autowired
    private PropietarioQueryService propietarioQueryService;

    @Autowired
    private MappingJackson2HttpMessageConverter jacksonMessageConverter;

    @Autowired
    private PageableHandlerMethodArgumentResolver pageableArgumentResolver;

    @Autowired
    private ExceptionTranslator exceptionTranslator;

    @Autowired
    private EntityManager em;

    private MockMvc restPropietarioMockMvc;

    private Propietario propietario;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        final PropietarioResource propietarioResource = new PropietarioResource(propietarioService, propietarioQueryService);
        this.restPropietarioMockMvc = MockMvcBuilders.standaloneSetup(propietarioResource)
            .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 Propietario createEntity(EntityManager em) {
        Propietario propietario = new Propietario()
            .nombre(DEFAULT_NOMBRE);
        return propietario;
    }

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

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

        // Create the Propietario
        PropietarioDTO propietarioDTO = propietarioMapper.toDto(propietario);
        restPropietarioMockMvc.perform(post("/api/propietarios")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(propietarioDTO)))
            .andExpect(status().isCreated());

        // Validate the Propietario in the database
        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeCreate + 1);
        Propietario testPropietario = propietarioList.get(propietarioList.size() - 1);
        assertThat(testPropietario.getNombre()).isEqualTo(DEFAULT_NOMBRE);
    }

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

        // Create the Propietario with an existing ID
        propietario.setId(1L);
        PropietarioDTO propietarioDTO = propietarioMapper.toDto(propietario);

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

        // Validate the Propietario in the database
        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeCreate);
    }

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

        // Create the Propietario, which fails.
        PropietarioDTO propietarioDTO = propietarioMapper.toDto(propietario);

        restPropietarioMockMvc.perform(post("/api/propietarios")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(propietarioDTO)))
            .andExpect(status().isBadRequest());

        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeTest);
    }

    @Test
    @Transactional
    public void getAllPropietarios() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

    @Test
    @Transactional
    public void getPropietario() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

    @Test
    @Transactional
    public void getAllPropietariosByNombreIsEqualToSomething() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

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

    @Test
    @Transactional
    public void getAllPropietariosByNombreIsInShouldWork() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

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

    @Test
    @Transactional
    public void getAllPropietariosByNombreIsNullOrNotNull() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

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

    @Test
    @Transactional
    public void getAllPropietariosByUsuarioIsEqualToSomething() throws Exception {
        // Initialize the database
        User usuario = UserResourceIntTest.createEntity(em);
        em.persist(usuario);
        em.flush();
        propietario.setUsuario(usuario);
        propietarioRepository.saveAndFlush(propietario);
        Long usuarioId = usuario.getId();

        // Get all the propietarioList where usuario equals to usuarioId
        defaultPropietarioShouldBeFound("usuarioId.equals=" + usuarioId);

        // Get all the propietarioList where usuario equals to usuarioId + 1
        defaultPropietarioShouldNotBeFound("usuarioId.equals=" + (usuarioId + 1));
    }

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

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

    @Test
    @Transactional
    public void updatePropietario() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

        // Update the propietario
        Propietario updatedPropietario = propietarioRepository.findById(propietario.getId()).get();
        // Disconnect from session so that the updates on updatedPropietario are not directly saved in db
        em.detach(updatedPropietario);
        updatedPropietario
            .nombre(UPDATED_NOMBRE);
        PropietarioDTO propietarioDTO = propietarioMapper.toDto(updatedPropietario);

        restPropietarioMockMvc.perform(put("/api/propietarios")
            .contentType(TestUtil.APPLICATION_JSON_UTF8)
            .content(TestUtil.convertObjectToJsonBytes(propietarioDTO)))
            .andExpect(status().isOk());

        // Validate the Propietario in the database
        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeUpdate);
        Propietario testPropietario = propietarioList.get(propietarioList.size() - 1);
        assertThat(testPropietario.getNombre()).isEqualTo(UPDATED_NOMBRE);
    }

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

        // Create the Propietario
        PropietarioDTO propietarioDTO = propietarioMapper.toDto(propietario);

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

        // Validate the Propietario in the database
        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeUpdate + 1);
    }

    @Test
    @Transactional
    public void deletePropietario() throws Exception {
        // Initialize the database
        propietarioRepository.saveAndFlush(propietario);

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

        // Get the propietario
        restPropietarioMockMvc.perform(delete("/api/propietarios/{id}", propietario.getId())
            .accept(TestUtil.APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());

        // Validate the database is empty
        List<Propietario> propietarioList = propietarioRepository.findAll();
        assertThat(propietarioList).hasSize(databaseSizeBeforeDelete - 1);
    }

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

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

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