package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBCropQueryService;
import vn.azteam.tpf.service.TBGuidelineService;
import vn.azteam.tpf.service.UserService;
import vn.azteam.tpf.service.dto.*;
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.TBGuidelineQueryService;
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.time.Instant;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Optional;

import vn.azteam.tpf.service.util.UserRoleUtil;

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

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

    private static final String ENTITY_NAME = "tBGuideline";

    private final TBGuidelineService tBGuidelineService;

    private final TBGuidelineQueryService tBGuidelineQueryService;

    private final UserService userService;

    private final TBCropQueryService tBCropQueryService;

    private final UserRoleUtil userRoleUtil;

    private final PageableUtil pageableUtil;

    public TBGuidelineResource(
        TBGuidelineService tBGuidelineService,
        TBGuidelineQueryService tBGuidelineQueryService,
        UserRoleUtil userRoleUtil,
        UserService userService,
        TBCropQueryService tBCropQueryService, PageableUtil pageableUtil) {
        this.tBGuidelineService = tBGuidelineService;
        this.tBGuidelineQueryService = tBGuidelineQueryService;
        this.userService = userService;
        this.userRoleUtil = userRoleUtil;
        this.tBCropQueryService = tBCropQueryService;
        this.pageableUtil = pageableUtil;
    }

    /**
     * POST  /tb-guidelines : Create a new tBGuideline.
     *
     * @param tBGuidelineDTO the tBGuidelineDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBGuidelineDTO, or with status 400 (Bad Request) if the tBGuideline has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-guidelines")
    @Timed
    public ResponseEntity<TBGuidelineDTO> createTBGuideline(@RequestBody TBGuidelineDTO tBGuidelineDTO) throws URISyntaxException {
        log.debug("REST request to save TBGuideline : {}", tBGuidelineDTO);
        if (tBGuidelineDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBGuideline cannot already have an ID", ENTITY_NAME, "idexists");
        }
        //Set created date to current timestamp
        tBGuidelineDTO.setCreatedDate(Instant.now());
        //Set created by to current user login
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        tBGuidelineDTO.setTbCustomerId(null);
        if (currentUser.getCustomerId() != null) {
            tBGuidelineDTO.setTbCustomerId(currentUser.getCustomerId());
        }
        tBGuidelineDTO.setCreatedById(currentUser.getUserId());

        TBGuidelineDTO result = tBGuidelineService.save(tBGuidelineDTO);
        return ResponseEntity.created(new URI("/api/tb-guidelines/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tb-guidelines : Updates an existing tBGuideline.
     *
     * @param tBGuidelineDTO the tBGuidelineDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBGuidelineDTO,
     * or with status 400 (Bad Request) if the tBGuidelineDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBGuidelineDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-guidelines")
    @Timed
    public ResponseEntity<TBGuidelineDTO> updateTBGuideline(@RequestBody TBGuidelineDTO tBGuidelineDTO) throws URISyntaxException {
        log.debug("REST request to update TBGuideline : {}", tBGuidelineDTO);
        if (tBGuidelineDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        TBGuidelineDTO tbGuidelineDTOUpdate = tBGuidelineService.findOne(tBGuidelineDTO.getId()).get();
        if (tbGuidelineDTOUpdate == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "guidelinenull");
        }
        tbGuidelineDTOUpdate.setName(tBGuidelineDTO.getName().isEmpty() ? tbGuidelineDTOUpdate.getName() : tBGuidelineDTO.getName());
        tbGuidelineDTOUpdate.setDescription(tBGuidelineDTO.getDescription().isEmpty() ? tbGuidelineDTOUpdate.getDescription() : tBGuidelineDTO.getDescription());
        tbGuidelineDTOUpdate.setCode(tBGuidelineDTO.getCode().isEmpty() ? tbGuidelineDTOUpdate.getCode() : tBGuidelineDTO.getCode());
        tbGuidelineDTOUpdate.setDuration(tBGuidelineDTO.getDuration() == null ? tbGuidelineDTOUpdate.getDuration() : tBGuidelineDTO.getDuration());
        //Set created date to current timestamp
        tbGuidelineDTOUpdate.setModifiedDate(Instant.now());
        //Set created by to current user login
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            if(tbGuidelineDTOUpdate.getTbCustomerId() == null
                || tbGuidelineDTOUpdate.getTbCustomerId() != currentUser.getCustomerId()){
                throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
            }
        }
        tbGuidelineDTOUpdate.setModifiedById(currentUser.getUserId());

        TBGuidelineDTO result = tBGuidelineService.save(tbGuidelineDTOUpdate);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBGuidelineDTO.getId().toString()))
            .body(result);
    }

    @PutMapping("/tb-guidelines-advance")
    @Timed
    public ResponseEntity<TBGuidelineDTO> updateFullInfoGuideline(@RequestBody GuidelineWrapperDTO tBGuidelineWrapperDTO) throws URISyntaxException {
        log.debug("REST request to update FullInfoGuideline : {}", tBGuidelineWrapperDTO);
        if (tBGuidelineWrapperDTO.getGuideline() == null || tBGuidelineWrapperDTO.getGuideline().getId() == null) {
            throw new BadRequestAlertException("Invalid guideline.id", ENTITY_NAME, "idnull");
        }
        //Set created by to current user login
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null
            && null == tBGuidelineWrapperDTO.getGuideline().getTbCustomerId()
            && currentUser.getCustomerId() != tBGuidelineWrapperDTO.getGuideline().getTbCustomerId()){
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        TBGuidelineDTO result = tBGuidelineQueryService.updateFullInfoGuideline(tBGuidelineWrapperDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBGuidelineWrapperDTO.getGuideline().getId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-guidelines : get all the tBGuidelines.
     *
     * @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 tBGuidelines in body
     */
    @GetMapping("/tb-guidelines")
    @Timed
    public ResponseEntity<List<TBGuidelineDTO>> getAllTBGuidelines(TBGuidelineCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBGuidelines by criteria: {}", criteria);
        Page<TBGuidelineDTO> page = tBGuidelineQueryService.findByCriteria(criteria, pageable);
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            List<TBGuidelineDTO> tbGuidelineDTOList = page.getContent().stream()
                .filter(item -> item.getTbCustomerId() == currentUser.getCustomerId() || item.getTbCustomerId() == null)
                .collect(Collectors.toList());
            page = pageableUtil.changeTBGuidelineDTODTOToPageFromList(tbGuidelineDTOList, pageable);
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-guidelines");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-guidelines/count : count all the tBGuidelines.
     *
     * @param criteria the criterias which the requested entities should match
     * @return the ResponseEntity with status 200 (OK) and the count in body
     */
    @GetMapping("/tb-guidelines/count")
    @Timed
    public ResponseEntity<Long> countTBGuidelines(TBGuidelineCriteria criteria) {
        log.debug("REST request to count TBGuidelines by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBGuidelineQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-guidelines/:id : get the "id" tBGuideline.
     *
     * @param id the id of the tBGuidelineDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBGuidelineDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-guidelines/{id}")
    @Timed
    public ResponseEntity<TBGuidelineDTO> getTBGuideline(@PathVariable Long id) {
        log.debug("REST request to get TBGuideline : {}", id);
        Optional<TBGuidelineDTO> tBGuidelineDTO = tBGuidelineService.findOne(id);
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null
            && null != tBGuidelineDTO.get().getTbCustomerId()
            && currentUser.getCustomerId() != tBGuidelineDTO.get().getTbCustomerId()){
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        return ResponseUtil.wrapOrNotFound(tBGuidelineDTO);
    }

    @GetMapping("/tb-guidelines-advance/{id}")
    @Timed
    public ResponseEntity<GuidelineWrapperDTO> getFullInfoGuideline(@PathVariable Long id) {
        log.debug("REST request to get FullInfoGuideline : {}", id);
        Optional<GuidelineWrapperDTO> tBGuidelineDTO = tBGuidelineQueryService.getFullInfoGuideline(id);
        return ResponseUtil.wrapOrNotFound(tBGuidelineDTO);
    }

    /**
     * DELETE  /tb-guidelines/:id : delete the "id" tBGuideline.
     *
     * @param id the id of the tBGuidelineDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-guidelines/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBGuideline(@PathVariable Long id) {
        log.debug("REST request to delete TBGuideline : {}", id);
        TBGuidelineDTO tBGuidelineDTO = tBGuidelineService.findOne(id).get();
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null
            && (null == tBGuidelineDTO.getTbCustomerId()
            || currentUser.getCustomerId() != tBGuidelineDTO.getTbCustomerId())){
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }

        TBCropCriteria tbCropCriteria = new TBCropCriteria();
        LongFilter guidelineIdFilter = new LongFilter();
        guidelineIdFilter.setEquals(id);
        tbCropCriteria.setTbGuidelineId(guidelineIdFilter);
        List<TBCropDTO> crops = tBCropQueryService.findByCriteria(tbCropCriteria);
        if (!crops.isEmpty()) {
            throw new BadRequestAlertException("1046", ENTITY_NAME, "1046");
        }

        tBGuidelineDTO.setDeletedDate(Instant.now());
        tBGuidelineDTO.setDeletedById(currentUser.getId());
        tBGuidelineService.save(tBGuidelineDTO);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-guidelines?query=:query : search for the tBGuideline corresponding
     * to the query.
     *
     * @param query    the query of the tBGuideline search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-guidelines")
    @Timed
    public ResponseEntity<List<TBGuidelineDTO>> searchTBGuidelines(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBGuidelines for query {}", query);
        Page<TBGuidelineDTO> page = tBGuidelineQueryService.searchTBGuidelines(query, pageable);
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            List<TBGuidelineDTO> tbGuidelineDTOList = page.getContent().stream()
                .filter(item -> item.getTbCustomerId() == currentUser.getCustomerId() || item.getTbCustomerId() == null)
                .collect(Collectors.toList());
            page = pageableUtil.changeTBGuidelineDTODTOToPageFromList(tbGuidelineDTOList, pageable);
        }
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-guidelines");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
