package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBProductBlockDetailsService;
import vn.azteam.tpf.service.TBProductStockUpdateQueryService;
import vn.azteam.tpf.service.util.PageableUtil;
import vn.azteam.tpf.service.util.UserRoleUtil;
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.TBProductBlockDetailsDTO;
import vn.azteam.tpf.service.dto.TBProductStockUpdateDTO;
import vn.azteam.tpf.service.dto.ProductBlockUpdateDTO;
import vn.azteam.tpf.service.dto.TBProductBlockDetailsCriteria;
import vn.azteam.tpf.Constants.Constants.STOCK_UPDATE_ACTION;
import vn.azteam.tpf.service.TBProductBlockDetailsQueryService;
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;

import javax.validation.Valid;

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

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

    private static final String ENTITY_NAME = "tBProductBlockDetails";

    private final TBProductBlockDetailsService tBProductBlockDetailsService;

    private final TBProductBlockDetailsQueryService tBProductBlockDetailsQueryService;

    private final TBProductStockUpdateQueryService tbProductStockUpdateQueryService;

    private final UserRoleUtil userRoleUtil;

    private final PageableUtil pageableUtil;

    public TBProductBlockDetailsResource(TBProductBlockDetailsService tBProductBlockDetailsService,
                                         TBProductBlockDetailsQueryService tBProductBlockDetailsQueryService,
                                         TBProductStockUpdateQueryService tbProductStockUpdateQueryService, UserRoleUtil userRoleUtil, PageableUtil pageableUtil) {
        this.tBProductBlockDetailsService = tBProductBlockDetailsService;
        this.tBProductBlockDetailsQueryService = tBProductBlockDetailsQueryService;
        this.tbProductStockUpdateQueryService = tbProductStockUpdateQueryService;
        this.userRoleUtil = userRoleUtil;
        this.pageableUtil = pageableUtil;
    }

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

    /**
     * PUT  /tb-product-block-details : Updates an existing tBProductBlockDetails.
     *
     * @param tBProductBlockDetailsDTO the tBProductBlockDetailsDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBProductBlockDetailsDTO,
     * or with status 400 (Bad Request) if the tBProductBlockDetailsDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBProductBlockDetailsDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-product-block-details")
    @Timed
    public ResponseEntity<TBProductBlockDetailsDTO> updateTBProductBlockDetails(@RequestBody TBProductBlockDetailsDTO tBProductBlockDetailsDTO) throws URISyntaxException {
        log.debug("REST request to update TBProductBlockDetails : {}", tBProductBlockDetailsDTO);
        if (tBProductBlockDetailsDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        Optional<TBProductBlockDetailsDTO> dbProductBlockDetails = tBProductBlockDetailsService.findOne(tBProductBlockDetailsDTO.getId());
        if(!userRoleUtil.currentUserHasPermissionByCropId(dbProductBlockDetails.get().getTbCropId())){
            throw new BadRequestAlertException("1057", ENTITY_NAME, "1057");
        }
        TBProductBlockDetailsDTO result = tBProductBlockDetailsService.save(tBProductBlockDetailsDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBProductBlockDetailsDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-product-block-details : get all the tBProductBlockDetails.
     *
     * @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 tBProductBlockDetails in body
     */
    @GetMapping("/tb-product-block-details")
    @Timed
    public ResponseEntity<List<TBProductBlockDetailsDTO>> getAllTBProductBlockDetails(TBProductBlockDetailsCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBProductBlockDetails by criteria: {}", criteria);
        // Page<TBProductBlockDetailsDTO> page = tBProductBlockDetailsQueryService.findByCriteria(criteria, pageable);
        Page<TBProductBlockDetailsDTO> page = tBProductBlockDetailsQueryService.nativeSearch(criteria, pageable);
        if(page.getContent().size() > 0){
            List<TBProductBlockDetailsDTO> tbProductBlockDetailsDTOList = page.getContent().stream()
                .filter(item -> userRoleUtil.currentUserHasPermissionByCropId(item.getTbCropId()))
                .collect(Collectors.toList());
            page = pageableUtil.changeTBProductBlockDetailsDTOToPageFromList(tbProductBlockDetailsDTOList, pageable);
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-product-block-details");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-product-block-details/count : count all the tBProductBlockDetails.
    *
    * @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-block-details/count")
    @Timed
    public ResponseEntity<Long> countTBProductBlockDetails(TBProductBlockDetailsCriteria criteria) {
        log.debug("REST request to count TBProductBlockDetails by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBProductBlockDetailsQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-product-block-details/:id : get the "id" tBProductBlockDetails.
     *
     * @param id the id of the tBProductBlockDetailsDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBProductBlockDetailsDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-product-block-details/{id}")
    @Timed
    public ResponseEntity<TBProductBlockDetailsDTO> getTBProductBlockDetails(@PathVariable Long id) {
        log.debug("REST request to get TBProductBlockDetails : {}", id);
        Optional<TBProductBlockDetailsDTO> tBProductBlockDetailsDTO = tBProductBlockDetailsService.findOne(id);
        if(!userRoleUtil.currentUserHasPermissionByCropId(tBProductBlockDetailsDTO.get().getTbCropId())){
            throw new BadRequestAlertException("1057", ENTITY_NAME, "1057");
        }
        TBProductStockUpdateDTO tbProductStockUpdateDTO = tbProductStockUpdateQueryService.findImportActionOneByBlockId(id);
        tBProductBlockDetailsDTO.get().setDescription(tbProductStockUpdateDTO.getDescription());
        return ResponseUtil.wrapOrNotFound(tBProductBlockDetailsDTO);
    }

    /**
     * DELETE  /tb-product-block-details/:id : delete the "id" tBProductBlockDetails.
     *
     * @param id the id of the tBProductBlockDetailsDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-product-block-details/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBProductBlockDetails(@PathVariable Long id) {
        log.debug("REST request to delete TBProductBlockDetails : {}", id);
        Optional<TBProductBlockDetailsDTO> optional = tBProductBlockDetailsService.findOne(id);
        if(!userRoleUtil.currentUserHasPermissionByCropId(optional.get().getTbCropId())){
            throw new BadRequestAlertException("1057", ENTITY_NAME, "1057");
        }
        if (!optional.isPresent()) {
            throw new BadRequestAlertException("Not found entity", ENTITY_NAME, "notfound");
        }
        tBProductBlockDetailsService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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


    /**
     * POST  /tb-product-block-details : Create a new tBProductBlockDetails.
     *
     * @param productBlockUpdateDTO the productBlockUpdateDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBProductBlockDetailsDTO, or with status 400 (Bad Request) if the tBProductBlockDetails has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-product-block-details/create-block-update")
    @Timed
    public ResponseEntity<TBProductBlockDetailsDTO> createProductBlockUpdate(@RequestBody @Valid ProductBlockUpdateDTO productBlockUpdateDTO) throws URISyntaxException {
        log.debug("REST request to save ProductBlockUpdateDTO : {}", productBlockUpdateDTO);
        validateCreateProductBlockUpdate(productBlockUpdateDTO);
        TBProductBlockDetailsDTO result = tBProductBlockDetailsService.createProductBlockUpdate(productBlockUpdateDTO);
        if (result == null) {
            throw new BadRequestAlertException("Invalid request or not implement this action", ENTITY_NAME, "invalidrequest");
        }
        return ResponseEntity.created(new URI("/api/tb-product-block-details/create-block-update" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    private void validateCreateProductBlockUpdate(ProductBlockUpdateDTO productBlockUpdateDTO) {
        if (productBlockUpdateDTO.getAction() == STOCK_UPDATE_ACTION.EXPORT.getValue()) {
            if (productBlockUpdateDTO.getProductBlockDetailsId() == null) {
                throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "exportactionrequireid");
            }

            Optional<TBProductBlockDetailsDTO> optional = tBProductBlockDetailsService
                .findOne(productBlockUpdateDTO.getProductBlockDetailsId());

            if (!optional.isPresent()) {
                throw new BadRequestAlertException("Not found", ENTITY_NAME, "notfound");
            }

            productBlockUpdateDTO.setProductBlockDetailsDTO(optional.get());

            TBProductStockUpdateDTO tbProductStockUpdateDTO = tbProductStockUpdateQueryService
                .findImportActionOneByBlockId(productBlockUpdateDTO.getProductBlockDetailsId());

            if (tbProductStockUpdateDTO == null) {
                throw new BadRequestAlertException("Not found block quantity", ENTITY_NAME, "notfoundblockquantity");
            }

            if (productBlockUpdateDTO.getQuantity() > tbProductStockUpdateDTO.getQuantity()) {
                throw new BadRequestAlertException("Quantity must less than block quantity", ENTITY_NAME, "qmustlesthanbq");
            }
        }
    }
}
