package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBProductStockUpdateService;
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.TBProductStockUpdateDTO;
import vn.azteam.tpf.service.dto.TBProductStockUpdateCriteria;
import vn.azteam.tpf.Constants.Constants.PRODUCT_STOCK_UPDATE_ACTION;
import vn.azteam.tpf.service.TBProductBlockDetailsService;
import vn.azteam.tpf.service.TBProductStockUpdateQueryService;
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 TBProductStockUpdate.
 */
@RestController
@RequestMapping("/api")
public class TBProductStockUpdateResource {

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

    private static final String ENTITY_NAME = "tBProductStockUpdate";

    private final TBProductStockUpdateService tBProductStockUpdateService;

    private final TBProductStockUpdateQueryService tBProductStockUpdateQueryService;

    private final TBProductBlockDetailsService tbProductBlockDetailsService;

    public TBProductStockUpdateResource(TBProductStockUpdateService tBProductStockUpdateService,
                                        TBProductStockUpdateQueryService tBProductStockUpdateQueryService,
                                        TBProductBlockDetailsService tbProductBlockDetailsService) {
        this.tBProductStockUpdateService = tBProductStockUpdateService;
        this.tBProductStockUpdateQueryService = tBProductStockUpdateQueryService;
        this.tbProductBlockDetailsService = tbProductBlockDetailsService;
    }

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

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

    /**
     * GET  /tb-product-stock-updates : get all the tBProductStockUpdates.
     *
     * @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 tBProductStockUpdates in body
     */
    @GetMapping("/tb-product-stock-updates")
    @Timed
    public ResponseEntity<List<TBProductStockUpdateDTO>> getAllTBProductStockUpdates(TBProductStockUpdateCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBProductStockUpdates by criteria: {}", criteria);
        Page<TBProductStockUpdateDTO> page = tBProductStockUpdateQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-product-stock-updates");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-product-stock-updates/count : count all the tBProductStockUpdates.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-product-stock-updates/count")
    @Timed
    public ResponseEntity<Long> countTBProductStockUpdates(TBProductStockUpdateCriteria criteria) {
        log.debug("REST request to count TBProductStockUpdates by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBProductStockUpdateQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-product-stock-updates/:id : get the "id" tBProductStockUpdate.
     *
     * @param id the id of the tBProductStockUpdateDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBProductStockUpdateDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-product-stock-updates/{id}")
    @Timed
    public ResponseEntity<TBProductStockUpdateDTO> getTBProductStockUpdate(@PathVariable Long id) {
        log.debug("REST request to get TBProductStockUpdate : {}", id);
        Optional<TBProductStockUpdateDTO> tBProductStockUpdateDTO = tBProductStockUpdateService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBProductStockUpdateDTO);
    }

    /**
     * DELETE  /tb-product-stock-updates/:id : delete the "id" tBProductStockUpdate.
     *
     * @param id the id of the tBProductStockUpdateDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-product-stock-updates/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBProductStockUpdate(@PathVariable Long id) {
        log.debug("REST request to delete TBProductStockUpdate : {}", id);
        Optional<TBProductStockUpdateDTO> optional = tBProductStockUpdateService.findOne(id);
        if (!optional.isPresent()) {
            new BadRequestAlertException("Not found entity", ENTITY_NAME, "notfound");
        }
        if (optional.get().getAction() == PRODUCT_STOCK_UPDATE_ACTION.IMPORT.getValue()) {
            new BadRequestAlertException("Cannot delete import stock", ENTITY_NAME, "cannotdeleteimportstock");
        }
        tBProductStockUpdateService.delete(id);
        tbProductBlockDetailsService
        .updateQuantityForProductBlockDetail(optional.get().getTbProductBlockDetailsId());
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
