package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBCountryService;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
import vn.azteam.tpf.web.rest.util.HeaderUtil;
import vn.azteam.tpf.web.rest.util.PaginationUtil;
import vn.azteam.tpf.service.dto.TBCountryDTO;
import vn.azteam.tpf.service.dto.TBCountryCriteria;
import vn.azteam.tpf.service.TBCountryQueryService;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * REST controller for managing TBCountry.
 */
@RestController
@RequestMapping("/api")
public class TBCountryResource {

    private final Logger log = LoggerFactory.getLogger(TBCountryResource.class);

    private static final String ENTITY_NAME = "tBCountry";

    private final TBCountryService tBCountryService;

    private final TBCountryQueryService tBCountryQueryService;

    public TBCountryResource(TBCountryService tBCountryService, TBCountryQueryService tBCountryQueryService) {
        this.tBCountryService = tBCountryService;
        this.tBCountryQueryService = tBCountryQueryService;
    }

    /**
     * POST  /tb-countries : Create a new tBCountry.
     *
     * @param tBCountryDTO the tBCountryDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBCountryDTO, or with status 400 (Bad Request) if the tBCountry has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-countries")
    @Timed
    public ResponseEntity<TBCountryDTO> createTBCountry(@RequestBody TBCountryDTO tBCountryDTO) throws URISyntaxException {
        log.debug("REST request to save TBCountry : {}", tBCountryDTO);
        if (tBCountryDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBCountry cannot already have an ID", ENTITY_NAME, "idexists");
        }
        TBCountryDTO result = tBCountryService.save(tBCountryDTO);
        return ResponseEntity.created(new URI("/api/tb-countries/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tb-countries : Updates an existing tBCountry.
     *
     * @param tBCountryDTO the tBCountryDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBCountryDTO,
     * or with status 400 (Bad Request) if the tBCountryDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBCountryDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-countries")
    @Timed
    public ResponseEntity<TBCountryDTO> updateTBCountry(@RequestBody TBCountryDTO tBCountryDTO) throws URISyntaxException {
        log.debug("REST request to update TBCountry : {}", tBCountryDTO);
        if (tBCountryDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        TBCountryDTO result = tBCountryService.save(tBCountryDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBCountryDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-countries : get all the tBCountries.
     *
     * @param pageable the pagination information
     * @param criteria the criterias which the requested entities should match
     * @return the ResponseEntity with status 200 (OK) and the list of tBCountries in body
     */
    @GetMapping("/tb-countries")
    @Timed
    public ResponseEntity<List<TBCountryDTO>> getAllTBCountries(TBCountryCriteria criteria, Pageable pageable,
                                                                @RequestParam(value = "query", required=false) String query) {
        log.debug("REST request to get TBCountries by criteria: {}", criteria);
        Page<TBCountryDTO> page = tBCountryQueryService.getTBCountries(query, criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-countries");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-countries/count : count all the tBCountries.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-countries/count")
    @Timed
    public ResponseEntity<Long> countTBCountries(TBCountryCriteria criteria) {
        log.debug("REST request to count TBCountries by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBCountryQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-countries/:id : get the "id" tBCountry.
     *
     * @param id the id of the tBCountryDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBCountryDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-countries/{id}")
    @Timed
    public ResponseEntity<TBCountryDTO> getTBCountry(@PathVariable Long id) {
        log.debug("REST request to get TBCountry : {}", id);
        Optional<TBCountryDTO> tBCountryDTO = tBCountryService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBCountryDTO);
    }

    /**
     * DELETE  /tb-countries/:id : delete the "id" tBCountry.
     *
     * @param id the id of the tBCountryDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-countries/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBCountry(@PathVariable Long id) {
        log.debug("REST request to delete TBCountry : {}", id);
        tBCountryService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-countries?query=:query : search for the tBCountry corresponding
     * to the query.
     *
     * @param query the query of the tBCountry search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-countries")
    @Timed
    public ResponseEntity<List<TBCountryDTO>> searchTBCountries(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBCountries for query {}", query);
        Page<TBCountryDTO> page = tBCountryService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-countries");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
