package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBDistrictService;
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.TBDistrictDTO;
import vn.azteam.tpf.service.dto.TBDistrictCriteria;
import vn.azteam.tpf.service.TBDistrictQueryService;
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 TBDistrict.
 */
@RestController
@RequestMapping("/api")
public class TBDistrictResource {

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

    private static final String ENTITY_NAME = "tBDistrict";

    private final TBDistrictService tBDistrictService;

    private final TBDistrictQueryService tBDistrictQueryService;

    public TBDistrictResource(TBDistrictService tBDistrictService, TBDistrictQueryService tBDistrictQueryService) {
        this.tBDistrictService = tBDistrictService;
        this.tBDistrictQueryService = tBDistrictQueryService;
    }

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

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

    /**
     * GET  /tb-districts : get all the tBDistricts.
     *
     * @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 tBDistricts in body
     */
    @GetMapping("/tb-districts")
    @Timed
    public ResponseEntity<List<TBDistrictDTO>> getAllTBDistricts(TBDistrictCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBDistricts by criteria: {}", criteria);
        Page<TBDistrictDTO> page = tBDistrictQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-districts");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-districts-by-city/{cityId} : get all the tBDistricts by city.
     *
     * @param cityId the city id
     * @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 tBDistricts in body
     */
    @GetMapping("/tb-districts-by-city/{cityId}")
    @Timed
    public ResponseEntity<List<TBDistrictDTO>> getDistrictsByCity(@PathVariable("cityId") Long cityId, TBDistrictCriteria criteria, Pageable pageable,
                                                                  @RequestParam(value = "query", required=false) String query) {
        log.debug("REST request to get TBDistricts by city by criteria: {}", criteria);

//        LongFilter cityFilter = new LongFilter();
//        cityFilter.setEquals(cityId);
//        criteria.setTbCityId(cityFilter);

//        Page<TBDistrictDTO> page = tBDistrictQueryService.findByCriteria(criteria, pageable);
        Page<TBDistrictDTO> page = tBDistrictQueryService.getTbDistrictByCity(cityId, query, criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-districts-by-city");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

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

    /**
     * GET  /tb-districts/:id : get the "id" tBDistrict.
     *
     * @param id the id of the tBDistrictDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBDistrictDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-districts/{id}")
    @Timed
    public ResponseEntity<TBDistrictDTO> getTBDistrict(@PathVariable Long id) {
        log.debug("REST request to get TBDistrict : {}", id);
        Optional<TBDistrictDTO> tBDistrictDTO = tBDistrictService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBDistrictDTO);
    }

    /**
     * DELETE  /tb-districts/:id : delete the "id" tBDistrict.
     *
     * @param id the id of the tBDistrictDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-districts/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBDistrict(@PathVariable Long id) {
        log.debug("REST request to delete TBDistrict : {}", id);
        tBDistrictService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
