package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBDetailUserService;
import vn.azteam.tpf.service.TBRoleService;
import vn.azteam.tpf.service.UserService;
import vn.azteam.tpf.service.dto.TBRoleDTO;
import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.service.util.PageableUtil;
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.TBDetailUserDTO;
import vn.azteam.tpf.service.dto.TBDetailUserCriteria;
import vn.azteam.tpf.service.TBDetailUserQueryService;
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 TBDetailUser.
 */
@RestController
@RequestMapping("/api")
public class TBDetailUserResource {

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

    private static final String ENTITY_NAME = "tBDetailUser";

    private final TBDetailUserService tBDetailUserService;

    private final UserService userService;

    private final TBDetailUserQueryService tBDetailUserQueryService;

    private final PageableUtil pageableUtil;

    private final TBRoleService tbRoleService;

    public TBDetailUserResource(TBDetailUserService tBDetailUserService, UserService userService, TBDetailUserQueryService tBDetailUserQueryService, PageableUtil pageableUtil, TBRoleService tbRoleService) {
        this.tBDetailUserService = tBDetailUserService;
        this.userService = userService;
        this.tBDetailUserQueryService = tBDetailUserQueryService;
        this.pageableUtil = pageableUtil;
        this.tbRoleService = tbRoleService;
    }

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

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

    /**
     * GET  /tb-detail-users : get all the tBDetailUsers.
     *
     * @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 tBDetailUsers in body
     */
    @GetMapping("/tb-detail-users")
    @Timed
    public ResponseEntity<List<TBDetailUserDTO>> getAllTBDetailUsers(TBDetailUserCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBDetailUsers by criteria: {}", criteria);
        Page<TBDetailUserDTO> page = tBDetailUserQueryService.findByCriteria(criteria, pageable);
        List<TBDetailUserDTO> result = page.getContent();
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if(currentUser.getCustomerId() != null){
            result = result.stream()
                .filter(item -> item.getTbCustomerId() != null && item.getTbCustomerId() == currentUser.getCustomerId())
                .collect(Collectors.toList());
            page = pageableUtil.changeTBDetailUserDTOToPageFromList(result,pageable);
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-detail-users");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-detail-users : get all the tBDetailUsers belong to a crop.
     *
     * @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 tBDetailUsers in body
     */
    @GetMapping("/tb-detail-users/crop/{cropId}")
    @Timed
    public ResponseEntity<List<TBDetailUserDTO>> getCropPersonInCharge(@PathVariable("cropId") Long cropId, TBDetailUserCriteria criteria, Pageable pageable) {
        log.debug("REST request to get CropPersonInCharge by criteria: {}", criteria);
        LongFilter cropFilter = new LongFilter();
        cropFilter.setEquals(cropId);
        criteria.setTbCropId(cropFilter);
        Page<TBDetailUserDTO> page = tBDetailUserQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-detail-users");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-detail-users/count : count all the tBDetailUsers.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-detail-users/count")
    @Timed
    public ResponseEntity<Long> countTBDetailUsers(TBDetailUserCriteria criteria) {
        log.debug("REST request to count TBDetailUsers by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBDetailUserQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-detail-users/:id : get the "id" tBDetailUser.
     *
     * @param id the id of the tBDetailUserDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBDetailUserDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-detail-users/{id}")
    @Timed
    public ResponseEntity<TBDetailUserDTO> getTBDetailUser(@PathVariable Long id) {
        log.debug("REST request to get TBDetailUser : {}", id);
        Optional<TBDetailUserDTO> tBDetailUserDTO = tBDetailUserService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBDetailUserDTO);
    }

    /**
     * DELETE  /tb-detail-users/:id : delete the "id" tBDetailUser.
     *
     * @param id the id of the tBDetailUserDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-detail-users/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBDetailUser(@PathVariable Long id) {
        log.debug("REST request to delete TBDetailUser : {}", id);
        tBDetailUserService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

}
