package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import org.springframework.transaction.annotation.Transactional;
import vn.azteam.tpf.service.*;
import vn.azteam.tpf.service.dto.*;
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 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 vn.azteam.tpf.service.util.UserRoleUtil;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.Optional;

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

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

    private static final String ENTITY_NAME = "tBStockUpdate";

    private final TBStockUpdateService tBStockUpdateService;

    private final TBStockUpdateQueryService tBStockUpdateQueryService;

    private final UserRoleUtil userRoleUtil;

    private final UserService userService;

    private final TBSuppliesService tBSuppliesService;

    private final TBSuppliesInWarehouseQueryService tBSuppliesInWarehouseQueryService;

    private final TBSuppliesUsingDetailsService tbSuppliesUsingDetailsService;

    private final TBSuppliesUsingDetailsQueryService tbSuppliesUsingDetailsQueryService;

    private final TBSuppliesInWarehouseService tBSuppliesInWarehouseService;

    public TBStockUpdateResource(TBStockUpdateService tBStockUpdateService,
                                 TBStockUpdateQueryService tBStockUpdateQueryService,
                                 UserRoleUtil userRoleUtil,
                                 UserService userService,
                                 TBSuppliesService tBSuppliesService,
                                 TBSuppliesInWarehouseQueryService tBSuppliesInWarehouseQueryService,
                                 TBSuppliesUsingDetailsService tbSuppliesUsingDetailsService,
                                 TBSuppliesUsingDetailsQueryService tbSuppliesUsingDetailsQueryService, TBSuppliesInWarehouseService tBSuppliesInWarehouseService) {
        this.tBStockUpdateService = tBStockUpdateService;
        this.tBStockUpdateQueryService = tBStockUpdateQueryService;
        this.userRoleUtil = userRoleUtil;
        this.userService = userService;
        this.tBSuppliesService = tBSuppliesService;
        this.tBSuppliesInWarehouseQueryService = tBSuppliesInWarehouseQueryService;
        this.tbSuppliesUsingDetailsService = tbSuppliesUsingDetailsService;
        this.tbSuppliesUsingDetailsQueryService = tbSuppliesUsingDetailsQueryService;
        this.tBSuppliesInWarehouseService = tBSuppliesInWarehouseService;
    }

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

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

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

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

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

    /**
     * DELETE  /tb-stock-updates/:id : delete the "id" tBStockUpdate.
     *
     * @param id the id of the tBStockUpdateDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-stock-updates/{id}")
    @Timed
    @Transactional(readOnly = false)
    public ResponseEntity<Void> deleteTBStockUpdate(@PathVariable Long id) {
        log.debug("REST request to delete TBStockUpdate : {}", id);
        TBStockUpdateDTO tBStockUpdateDTO = tBStockUpdateService.findOne(id).get();

        tBStockUpdateService.delete(id);

        TBSuppliesUsingDetailsCriteria criteria = new TBSuppliesUsingDetailsCriteria();

        LongFilter tbSuppliesInWarehouseIdFilter = new LongFilter();
        tbSuppliesInWarehouseIdFilter.setEquals(tBStockUpdateDTO.getTbSuppliesInWarehouseId());
        criteria.setTbSuppliesInWarehouseId(tbSuppliesInWarehouseIdFilter);

        LongFilter tbActivityIdFilter = new LongFilter();
        tbActivityIdFilter.setEquals(tBStockUpdateDTO.getTbActivityId());
        criteria.setTbActivityId(tbActivityIdFilter);

        LongFilter tbBlockDetailsIdFilter = new LongFilter();
        tbBlockDetailsIdFilter.setEquals(tBStockUpdateDTO.getTbBlockDetailsId());
        criteria.setTbBlockDetailsId(tbBlockDetailsIdFilter);

        List<TBSuppliesUsingDetailsDTO> tbSuppliesUsingDetailsDTOs = tbSuppliesUsingDetailsQueryService.findByCriteria(criteria);
        if(tbSuppliesUsingDetailsDTOs != null && tbSuppliesUsingDetailsDTOs.size() > 0) {
            TBSuppliesUsingDetailsDTO tbSuppliesUsingDetailsDTO = tbSuppliesUsingDetailsDTOs.get(0);
            tbSuppliesUsingDetailsService.delete(tbSuppliesUsingDetailsDTO.getId());
        }

        tBSuppliesInWarehouseQueryService.updateQuantityForTBSuppliesInWarehouseDTO(tBStockUpdateDTO.getTbSuppliesInWarehouseId());
        TBSuppliesInWarehouseDTO tbSuppliesInWarehouseDTO = tBSuppliesInWarehouseService.findOne(tBStockUpdateDTO.getTbSuppliesInWarehouseId()).get();
        tBSuppliesInWarehouseQueryService.updateQuantityForTBBlockDetailsDTO(tBStockUpdateDTO.getTbSuppliesInWarehouseId(), tBStockUpdateDTO.getTbBlockDetailsId(), tbSuppliesInWarehouseDTO.getTbSuppliesId());

        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-stock-updates?query=:query : search for the tBStockUpdate corresponding
     * to the query.
     *
     * @param query the query of the tBStockUpdate search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-stock-updates")
    @Timed
    public ResponseEntity<List<TBStockUpdateDTO>> searchTBStockUpdates(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBStockUpdates for query {}", query);
        Page<TBStockUpdateDTO> page = tBStockUpdateService.search(query, pageable);

        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-stock-updates");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    @GetMapping("/historySupplies/{suppliesId}")
    @Timed
    public ResponseEntity<List<TBStockUpdateDTO>> historySupplies(@PathVariable String suppliesId,
                                                                    TBStockUpdateCriteria criteria, Pageable pageable) {

        log.debug("REST request to get TBSupplies by criteria: {}", criteria);
        Long suppliesIdLong;
        suppliesIdLong = Long.parseLong(suppliesId);
        if (suppliesId == null){
            throw new BadRequestAlertException("Invalid suppliesId", ENTITY_NAME, "idnull");
        }
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        Optional<TBSuppliesDTO> suppliesDTO = tBSuppliesService.findOne(suppliesIdLong);
        if (currentUser.getCustomerId() != null
            && suppliesDTO.get().getTbCustomerId() != null
            && currentUser.getCustomerId() != suppliesDTO.get().getTbCustomerId()){
            throw new BadRequestAlertException("1013", ENTITY_NAME, "1013");
        }
        Page<TBStockUpdateDTO> page = tBStockUpdateQueryService.getHistoryTBStockUpdate(criteria, pageable, suppliesIdLong);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/historySupplies");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }
}
