package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import org.springframework.data.jpa.domain.Specification;
import vn.azteam.tpf.domain.TBSupplies;
import vn.azteam.tpf.service.TBCityService;
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.TBCityDTO;
import vn.azteam.tpf.service.dto.TBCityCriteria;
import vn.azteam.tpf.service.TBCityQueryService;
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;

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

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

    private static final String ENTITY_NAME = "tBCity";

    private final TBCityService tBCityService;

    private final TBCityQueryService tBCityQueryService;

    public TBCityResource(TBCityService tBCityService, TBCityQueryService tBCityQueryService) {
        this.tBCityService = tBCityService;
        this.tBCityQueryService = tBCityQueryService;
    }

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

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

    /**
     * GET  /tb-cities : get all the tBCities.
     *
     * @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 tBCities in body
     */
    @GetMapping("/tb-cities")
    @Timed
    public ResponseEntity<List<TBCityDTO>> getAllTBCities(TBCityCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBCities by criteria: {}", criteria);
        Page<TBCityDTO> page = tBCityQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-cities");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }


    /**
     * GET  /tb-cities-by-country/{countryId} : get all the tBCities by country.
     *
     * @param countryId the country 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 tBCities in body
     */
    @GetMapping("/tb-cities-by-country/{countryId}")
    @Timed
    public ResponseEntity<List<TBCityDTO>> getCitiesByCountry(@PathVariable("countryId") Long countryId, TBCityCriteria criteria, Pageable pageable,
                                                              @RequestParam(value = "query", required=false) String query) {
        log.debug("REST request to get cities by country by criteria: {}", criteria);
//
//        LongFilter countryFilter = new LongFilter();
//        countryFilter.setEquals(countryId);
//        criteria.setTbCountryId(countryFilter);

//        Page<TBCityDTO> page = tBCityQueryService.findByCriteria(criteria, pageable);
//        List<Long> ids = tBCityQueryService.getIdsTbCityByCountry(countryId, query);
//        LongFilter suppliesIdFilter = new LongFilter();
//        suppliesIdFilter.setIn(listSuppliesId);
//        criteria.setId(suppliesIdFilter);
//
//        final Specification<TBSupplies> specification = createSpecification(criteria);

        Page<TBCityDTO> page = tBCityQueryService.getTbCityByCountry(countryId, query, criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-cities-by-country");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }


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

    /**
     * GET  /tb-cities/:id : get the "id" tBCity.
     *
     * @param id the id of the tBCityDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBCityDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-cities/{id}")
    @Timed
    public ResponseEntity<TBCityDTO> getTBCity(@PathVariable Long id) {
        log.debug("REST request to get TBCity : {}", id);
        Optional<TBCityDTO> tBCityDTO = tBCityService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBCityDTO);
    }

    /**
     * DELETE  /tb-cities/:id : delete the "id" tBCity.
     *
     * @param id the id of the tBCityDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-cities/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBCity(@PathVariable Long id) {
        log.debug("REST request to delete TBCity : {}", id);
        tBCityService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
