package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.DoubleFilter;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBBlockDetailsService;
import vn.azteam.tpf.service.TBSuppliesInWarehouseQueryService;
import vn.azteam.tpf.service.dto.TBSuppliesInWarehouseDTO;
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.TBBlockDetailsDTO;
import vn.azteam.tpf.service.dto.TBBlockDetailsOptionDTO;
import vn.azteam.tpf.service.dto.TBBlockDetailsCriteria;
import vn.azteam.tpf.service.TBBlockDetailsQueryService;
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.Collectors;

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

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

    private static final String ENTITY_NAME = "tBBlockDetails";

    private final TBBlockDetailsService tBBlockDetailsService;

    private final TBBlockDetailsQueryService tBBlockDetailsQueryService;

    private final TBSuppliesInWarehouseQueryService tbSuppliesInWarehouseQueryService;

    public TBBlockDetailsResource(TBBlockDetailsService tBBlockDetailsService,
                                  TBBlockDetailsQueryService tBBlockDetailsQueryService,
                                  TBSuppliesInWarehouseQueryService tbSuppliesInWarehouseQueryService) {
        this.tBBlockDetailsService = tBBlockDetailsService;
        this.tBBlockDetailsQueryService = tBBlockDetailsQueryService;
        this.tbSuppliesInWarehouseQueryService = tbSuppliesInWarehouseQueryService;
    }

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

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

    /**
     * GET  /tb-block-details : get all the tBBlockDetails.
     *
     * @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 tBBlockDetails in body
     */
    @GetMapping("/tb-block-details")
    @Timed
    public ResponseEntity<List<TBBlockDetailsDTO>> getAllTBBlockDetails(TBBlockDetailsCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBBlockDetails by criteria: {}", criteria);
        Page<TBBlockDetailsDTO> page = tBBlockDetailsQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-block-details");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-block-details : get all the tBBlockDetails.
     *
     * @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 tBBlockDetails in body
     */
    @GetMapping("/tb-block-details/options")
    public ResponseEntity<List<TBBlockDetailsOptionDTO>> getAllTBBlockDetailsOptions(TBBlockDetailsCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBBlockDetails by criteria: {}", criteria);
        Page<TBBlockDetailsDTO> page = tBBlockDetailsQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-block-details");
        return ResponseEntity.ok().headers(headers).body(page.getContent()
            .stream()
            .map(i -> i.toOptionDto())
            .collect(Collectors.toList()));
    }

    /**
    * GET  /tb-block-details/count : count all the tBBlockDetails.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-block-details/count")
    @Timed
    public ResponseEntity<Long> countTBBlockDetails(TBBlockDetailsCriteria criteria) {
        log.debug("REST request to count TBBlockDetails by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBBlockDetailsQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-block-details/:id : get the "id" tBBlockDetails.
     *
     * @param id the id of the tBBlockDetailsDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBBlockDetailsDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-block-details/{id}")
    @Timed
    public ResponseEntity<TBBlockDetailsDTO> getTBBlockDetails(@PathVariable Long id) {
        log.debug("REST request to get TBBlockDetails : {}", id);
        Optional<TBBlockDetailsDTO> tBBlockDetailsDTO = tBBlockDetailsService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBBlockDetailsDTO);
    }

    /**
     * DELETE  /tb-block-details/:id : delete the "id" tBBlockDetails.
     *
     * @param id the id of the tBBlockDetailsDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-block-details/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBBlockDetails(@PathVariable Long id) {
        log.debug("REST request to delete TBBlockDetails : {}", id);
        tBBlockDetailsService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

    @GetMapping("/tb-block-details-by-supplies-in-warehouse-id/{tbSuppliesInWarehouseId}")
    public ResponseEntity<List<TBBlockDetailsDTO>> getAllTBBlockDetailsSuppliesAndEntityId(@PathVariable Long tbSuppliesInWarehouseId) {
        TBBlockDetailsCriteria criteria = new TBBlockDetailsCriteria();
        LongFilter longFilter = new LongFilter();
        longFilter.setEquals(tbSuppliesInWarehouseId);
        criteria.setTbSuppliesInWarehouseId(longFilter);

        DoubleFilter quantityFilter = new DoubleFilter();
        quantityFilter.setGreaterThan(0D);
        criteria.setQuantity(quantityFilter);

        List<TBBlockDetailsDTO> tbBlockDetailsDTOs = tBBlockDetailsQueryService.findByCriteria(criteria);
        return ResponseEntity.ok().headers(null).body(tbBlockDetailsDTOs);
    }

}
