package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBEquipmentHistoryService;
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.TBEquipmentHistoryDTO;
import vn.azteam.tpf.service.dto.TBEquipmentHistoryCriteria;
import vn.azteam.tpf.service.TBEquipmentHistoryQueryService;
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.time.Instant;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

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

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

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

    private static final String ENTITY_NAME = "tBEquipmentHistory";

    private final TBEquipmentHistoryService tBEquipmentHistoryService;

    private final TBEquipmentHistoryQueryService tBEquipmentHistoryQueryService;

    public TBEquipmentHistoryResource(TBEquipmentHistoryService tBEquipmentHistoryService, TBEquipmentHistoryQueryService tBEquipmentHistoryQueryService) {
        this.tBEquipmentHistoryService = tBEquipmentHistoryService;
        this.tBEquipmentHistoryQueryService = tBEquipmentHistoryQueryService;
    }

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

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

    /**
     * GET  /tb-equipment-histories : get all the tBEquipmentHistories.
     *
     * @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 tBEquipmentHistories in body
     */
    @GetMapping("/tb-equipment-histories")
    @Timed
    public ResponseEntity<List<TBEquipmentHistoryDTO>> getAllTBEquipmentHistories(TBEquipmentHistoryCriteria criteria, Pageable pageable,
                                                                                  @RequestParam(value = "startTime", required =false) Instant startTime,
                                                                                  @RequestParam(value = "endTime", required=false ) Instant endTime,
                                                                                  @RequestParam(value = "equipmentInWarehouseId", required=false ) Long equipmentInWarehouseId
    ) {
        log.debug("REST request to get TBEquipmentHistories by criteria: {}", criteria);
        Page<TBEquipmentHistoryDTO> page = tBEquipmentHistoryQueryService.getTBEquipmentHistories(criteria, pageable, startTime, endTime, equipmentInWarehouseId);
//        Page<TBEquipmentHistoryDTO> page = tBEquipmentHistoryQueryService.getTBEquipmentHistories(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-equipment-histories");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-equipment-histories/count : count all the tBEquipmentHistories.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-equipment-histories/count")
    @Timed
    public ResponseEntity<Long> countTBEquipmentHistories(TBEquipmentHistoryCriteria criteria) {
        log.debug("REST request to count TBEquipmentHistories by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBEquipmentHistoryQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-equipment-histories/:id : get the "id" tBEquipmentHistory.
     *
     * @param id the id of the tBEquipmentHistoryDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBEquipmentHistoryDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-equipment-histories/{id}")
    @Timed
    public ResponseEntity<TBEquipmentHistoryDTO> getTBEquipmentHistory(@PathVariable Long id) {
        log.debug("REST request to get TBEquipmentHistory : {}", id);
        Optional<TBEquipmentHistoryDTO> tBEquipmentHistoryDTO = tBEquipmentHistoryService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBEquipmentHistoryDTO);
    }

    /**
     * DELETE  /tb-equipment-histories/:id : delete the "id" tBEquipmentHistory.
     *
     * @param id the id of the tBEquipmentHistoryDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-equipment-histories/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBEquipmentHistory(@PathVariable Long id) {
        log.debug("REST request to delete TBEquipmentHistory : {}", id);
        tBEquipmentHistoryService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
