package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBProductUnitService;
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.TBProductUnitDTO;
import vn.azteam.tpf.service.dto.TBProductUnitCriteria;
import vn.azteam.tpf.service.TBProductUnitQueryService;
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 TBProductUnit.
 */
@RestController
@RequestMapping("/api")
public class TBProductUnitResource {

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

    private static final String ENTITY_NAME = "tBProductUnit";

    private final TBProductUnitService tBProductUnitService;

    private final TBProductUnitQueryService tBProductUnitQueryService;

    public TBProductUnitResource(TBProductUnitService tBProductUnitService, TBProductUnitQueryService tBProductUnitQueryService) {
        this.tBProductUnitService = tBProductUnitService;
        this.tBProductUnitQueryService = tBProductUnitQueryService;
    }

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

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

    /**
     * GET  /tb-product-units : get all the tBProductUnits.
     *
     * @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 tBProductUnits in body
     */
    @GetMapping("/tb-product-units")
    @Timed
    public ResponseEntity<List<TBProductUnitDTO>> getAllTBProductUnits(TBProductUnitCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBProductUnits by criteria: {}", criteria);
        Page<TBProductUnitDTO> page = tBProductUnitQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-product-units");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-product-units/count : count all the tBProductUnits.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-product-units/count")
    @Timed
    public ResponseEntity<Long> countTBProductUnits(TBProductUnitCriteria criteria) {
        log.debug("REST request to count TBProductUnits by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBProductUnitQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-product-units/:id : get the "id" tBProductUnit.
     *
     * @param id the id of the tBProductUnitDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBProductUnitDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-product-units/{id}")
    @Timed
    public ResponseEntity<TBProductUnitDTO> getTBProductUnit(@PathVariable Long id) {
        log.debug("REST request to get TBProductUnit : {}", id);
        Optional<TBProductUnitDTO> tBProductUnitDTO = tBProductUnitService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBProductUnitDTO);
    }

    /**
     * DELETE  /tb-product-units/:id : delete the "id" tBProductUnit.
     *
     * @param id the id of the tBProductUnitDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-product-units/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBProductUnit(@PathVariable Long id) {
        log.debug("REST request to delete TBProductUnit : {}", id);
        tBProductUnitService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
