package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBWardService;
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.TBWardDTO;
import vn.azteam.tpf.service.dto.TBWardCriteria;
import vn.azteam.tpf.service.TBWardQueryService;
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 TBWard.
 */
@RestController
@RequestMapping("/api")
public class TBWardResource {

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

    private static final String ENTITY_NAME = "tBWard";

    private final TBWardService tBWardService;

    private final TBWardQueryService tBWardQueryService;

    public TBWardResource(TBWardService tBWardService, TBWardQueryService tBWardQueryService) {
        this.tBWardService = tBWardService;
        this.tBWardQueryService = tBWardQueryService;
    }

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

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

    /**
     * GET  /tb-wards : get all the tBWards.
     *
     * @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 tBWards in body
     */
    @GetMapping("/tb-wards")
    @Timed
    public ResponseEntity<List<TBWardDTO>> getAllTBWards(TBWardCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBWards by criteria: {}", criteria);
        Page<TBWardDTO> page = tBWardQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-wards");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-wards : get all the tBWards.
     *
     * @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 tBWards in body
     */
    @GetMapping("/tb-wards-by-district/{districtId}")
    @Timed
    public ResponseEntity<List<TBWardDTO>> getWardsByDistrict(@PathVariable("districtId") Long districtId, TBWardCriteria criteria, Pageable pageable,
                                                              @RequestParam(value = "query", required=false) String query) {
        log.debug("REST request to get TBWards by district by criteria: {}", criteria);
        Page<TBWardDTO> page = tBWardQueryService.getTbWardsByDistrict(districtId, query, criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-wards-by-district");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

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

    /**
     * GET  /tb-wards/:id : get the "id" tBWard.
     *
     * @param id the id of the tBWardDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBWardDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-wards/{id}")
    @Timed
    public ResponseEntity<TBWardDTO> getTBWard(@PathVariable Long id) {
        log.debug("REST request to get TBWard : {}", id);
        Optional<TBWardDTO> tBWardDTO = tBWardService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBWardDTO);
    }

    /**
     * DELETE  /tb-wards/:id : delete the "id" tBWard.
     *
     * @param id the id of the tBWardDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-wards/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBWard(@PathVariable Long id) {
        log.debug("REST request to delete TBWard : {}", id);
        tBWardService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
