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.service.util.PageableUtil;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
import vn.azteam.tpf.web.rest.errors.ForbiddenException;
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 java.net.URI;
import java.net.URISyntaxException;

import java.util.List;
import java.util.stream.Collectors;
import java.util.Optional;

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

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

    private static final String ENTITY_NAME = "tBGuidelineDetails";

    private final TBGuidelineDetailsService tBGuidelineDetailsService;

    private final TBGuidelineDetailsQueryService tBGuidelineDetailsQueryService;

    private final UserService userService;

    private final TBGuidelineActivityService tbGuidelineActivityService;

    private final TBGuidelineService tBGuidelineService;

    private final TBGuidelineDetailsObjectUpdateService tbGDObjectUpdateService;

    private final TBGuidelineDetailsObjectUpdateQueryService tbGDObjectUpdateQueryService;

    private final TBSuppliesUsingDetailsService tbSuppliesUsingDetailsService;

    private final TBSuppliesUsingDetailsQueryService tbSuppliesUsingDetailsQueryService;

    private final TBActivityTypeService tbActivityTypeService;

    private final TBGuidelineActivityQueryService tbGuidelineActivityQueryService;

    private final PageableUtil pageableUtil;

    public TBGuidelineDetailsResource(TBGuidelineDetailsService tBGuidelineDetailsService,
                                      UserService userService,
                                      TBGuidelineService tBGuidelineService,
                                      TBGuidelineDetailsQueryService tBGuidelineDetailsQueryService,
                                      TBGuidelineActivityService tbGuidelineActivityService,
                                      TBGuidelineDetailsObjectUpdateService tbGDObjectUpdateService,
                                      TBGuidelineDetailsObjectUpdateQueryService tbGDObjectUpdateQueryService,
                                      TBSuppliesUsingDetailsService tbSuppliesUsingDetailsService,
                                      TBSuppliesUsingDetailsQueryService tbSuppliesUsingDetailsQueryService,
                                      TBActivityTypeService tbActivityTypeService,
                                      TBGuidelineActivityQueryService tbGuidelineActivityQueryService, PageableUtil pageableUtil) {
        this.tBGuidelineDetailsService = tBGuidelineDetailsService;
        this.userService = userService;
        this.tBGuidelineService = tBGuidelineService;
        this.tBGuidelineDetailsQueryService = tBGuidelineDetailsQueryService;
        this.tbGuidelineActivityService = tbGuidelineActivityService;
        this.tbGDObjectUpdateService = tbGDObjectUpdateService;
        this.tbGDObjectUpdateQueryService = tbGDObjectUpdateQueryService;
        this.tbSuppliesUsingDetailsService = tbSuppliesUsingDetailsService;
        this.tbSuppliesUsingDetailsQueryService = tbSuppliesUsingDetailsQueryService;
        this.tbActivityTypeService = tbActivityTypeService;
        this.tbGuidelineActivityQueryService = tbGuidelineActivityQueryService;
        this.pageableUtil = pageableUtil;
    }

    /**
     * POST  /tb-guideline-details : Create a new tBGuidelineDetails.
     *
     * @param tBGuidelineDetailsDTO the tBGuidelineDetailsDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBGuidelineDetailsDTO, or with status 400 (Bad Request) if the tBGuidelineDetails has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-guideline-details")
    @Timed
    public ResponseEntity<TBGuidelineDetailsDTO> createTBGuidelineDetails(@RequestBody TBGuidelineDetailsWrapperDTO tBGuidelineDetailsDTO) throws URISyntaxException {
        log.debug("REST request to save TBGuidelineDetails : {}", tBGuidelineDetailsDTO);
        if (tBGuidelineDetailsDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBGuidelineDetails cannot already have an ID", ENTITY_NAME, "idexists");
        }
        tBGuidelineDetailsQueryService.validateAgeDayRange(tBGuidelineDetailsDTO);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        Optional<TBGuidelineDTO> tBGuidelineDTO = tBGuidelineService.findOne(tBGuidelineDetailsDTO.getTbGuidelineId());
        if (currentUser.getCustomerId() != null
            && tBGuidelineDTO.get().getTbCustomerId() != null
            && tBGuidelineDTO.get().getTbCustomerId() != currentUser.getCustomerId()) {
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        tBGuidelineDetailsQueryService.validatePeriod(tBGuidelineDetailsDTO);
        TBGuidelineDetailsDTO result = tBGuidelineDetailsQueryService.createTBGuidelineDetails(tBGuidelineDetailsDTO);
        return ResponseEntity.created(new URI("/api/tb-guideline-details/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tb-guideline-details : Updates an existing tBGuidelineDetails.
     *
     * @param tBGuidelineDetailsDTO the tBGuidelineDetailsDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBGuidelineDetailsDTO,
     * or with status 400 (Bad Request) if the tBGuidelineDetailsDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBGuidelineDetailsDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-guideline-details")
    @Timed
    public ResponseEntity<TBGuidelineDetailsDTO> updateTBGuidelineDetails(@RequestBody TBGuidelineDetailsWrapperDTO tBGuidelineDetailsDTO) throws URISyntaxException {
        log.debug("REST request to update TBGuidelineDetails : {}", tBGuidelineDetailsDTO);
        if (tBGuidelineDetailsDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        tBGuidelineDetailsQueryService.validateAgeDayRange(tBGuidelineDetailsDTO);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        Optional<TBGuidelineDetailsDTO> tempTBGuidelineDetailsDTO = tBGuidelineDetailsService.findOne(tBGuidelineDetailsDTO.getId());
        if (currentUser.getCustomerId() != null
            && tempTBGuidelineDetailsDTO.get().getTbCustomerId() != null
            && tempTBGuidelineDetailsDTO.get().getTbCustomerId() != currentUser.getCustomerId()) {
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        tBGuidelineDetailsQueryService.validatePeriod(tBGuidelineDetailsDTO);
        TBGuidelineDetailsDTO result = tBGuidelineDetailsQueryService.updateTBGuidelineDetails(tBGuidelineDetailsDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBGuidelineDetailsDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-guideline-details : get all the tBGuidelineDetails.
     *
     * @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 tBGuidelineDetails in body
     */
    @GetMapping("/tb-guideline-details")
    @Timed
    public ResponseEntity<List<TBGuidelineDetailsDTO>> getAllTBGuidelineDetails(TBGuidelineDetailsCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBGuidelineDetails by criteria: {}", criteria);
        Page<TBGuidelineDetailsDTO> page = tBGuidelineDetailsQueryService.findByCriteria(criteria, pageable);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            List<TBGuidelineDetailsDTO> tTBGuidelineDetailsDTOList = page.getContent().stream()
                .filter(item -> item.getTbCustomerId() == currentUser.getCustomerId() || item.getTbCustomerId() == null)
                .collect(Collectors.toList());
            page = pageableUtil.changeTBGuidelineDetailsDTOToPageFromList(tTBGuidelineDetailsDTOList, pageable);
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-guideline-details");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-guideline-details/count : count all the tBGuidelineDetails.
     *
     * @param criteria the criterias which the requested entities should match
     * @return the ResponseEntity with status 200 (OK) and the count in body
     */
    @GetMapping("/tb-guideline-details/count")
    @Timed
    public ResponseEntity<Long> countTBGuidelineDetails(TBGuidelineDetailsCriteria criteria) {
        log.debug("REST request to count TBGuidelineDetails by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBGuidelineDetailsQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-guideline-details/:id : get the "id" tBGuidelineDetails.
     *
     * @param id the id of the tBGuidelineDetailsDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBGuidelineDetailsDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-guideline-details/{id}")
    @Timed
    public ResponseEntity<TBGuidelineDetailsWrapperDTO> getTBGuidelineDetails(@PathVariable Long id) {
        log.debug("REST request to get TBGuidelineDetails : {}", id);
        Optional<TBGuidelineDetailsWrapperDTO> tBGuidelineDetailsDTO = tBGuidelineDetailsQueryService.getTBGuidelineDetails(id);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        Optional<TBGuidelineDetailsDTO> tempTBGuidelineDetailsDTO = tBGuidelineDetailsService.findOne(id);
        if (currentUser.getCustomerId() != null
            && tempTBGuidelineDetailsDTO.get().getTbCustomerId() != null
            && tempTBGuidelineDetailsDTO.get().getTbCustomerId() != currentUser.getCustomerId()) {
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        return ResponseUtil.wrapOrNotFound(tBGuidelineDetailsDTO);
    }

    /**
     * DELETE  /tb-guideline-details/:id : delete the "id" tBGuidelineDetails.
     *
     * @param id the id of the tBGuidelineDetailsDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-guideline-details/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBGuidelineDetails(@PathVariable Long id) {
        log.debug("REST request to delete TBGuidelineDetails : {}", id);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        Optional<TBGuidelineDetailsDTO> tBGuidelineDetailsDTO = tBGuidelineDetailsService.findOne(id);
        if (currentUser.getCustomerId() != null
            && (tBGuidelineDetailsDTO.get().getTbCustomerId() == null
            || tBGuidelineDetailsDTO.get().getTbCustomerId() != currentUser.getCustomerId())) {
            throw new BadRequestAlertException("1020", ENTITY_NAME, "1020");
        }
        tBGuidelineDetailsQueryService.deleteTBGuidelineDetails(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-guideline-details?query=:query : search for the tBGuidelineDetails corresponding
     * to the query.
     *
     * @param query    the query of the tBGuidelineDetails search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-guideline-details")
    @Timed
    public ResponseEntity<List<TBGuidelineDetailsDTO>> searchTBGuidelineDetails(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBGuidelineDetails for query {}", query);
        Page<TBGuidelineDetailsDTO> page = tBGuidelineDetailsService.search(query, pageable);
        //@CUONGLT - Filter scope customer's data
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            List<TBGuidelineDetailsDTO> tBGuidelineDetailsDTOS = page.getContent().stream()
                .filter(item -> item.getTbCustomerId() == currentUser.getCustomerId() || item.getTbCustomerId() == null)
                .collect(Collectors.toList());
            page = pageableUtil.changeTBGuidelineDetailsDTOToPageFromList(tBGuidelineDetailsDTOS, pageable);
        }
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-guideline-details");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }


    @PostMapping("/duplicate-tb-guideline-details/{tbGuidelineDetailsId}")
    @Transactional(readOnly = false)
    @Timed
    public ResponseEntity<TBGuidelineDetailsWrapperDTO> duplicateTBGuidelineDetails(@PathVariable Long tbGuidelineDetailsId, @RequestBody TBGuidelineDetailsWrapperDTO duplicateTBGuidelineDetailsDTO) throws URISyntaxException {
        log.debug("REST request to duplicate TBGuidelineDetails : {}", tbGuidelineDetailsId);

        //Create tb_guideline_details
        TBGuidelineDetailsDTO duplicatedTBGuidelineDetailsDTO = tBGuidelineDetailsQueryService.createTBGuidelineDetails(duplicateTBGuidelineDetailsDTO);

        //Duplicate tb_limits of tb-guideline detail
        tBGuidelineDetailsQueryService.duplicateTBLimits(tbGuidelineDetailsId,duplicatedTBGuidelineDetailsDTO.getId());

        //Duplicate tb_guideline_activity
        tBGuidelineDetailsQueryService.duplicateTBGuidelineActivity(tbGuidelineDetailsId,duplicatedTBGuidelineDetailsDTO.getId());

        TBGuidelineDetailsWrapperDTO result = tBGuidelineDetailsQueryService.getTBGuidelineDetails(duplicatedTBGuidelineDetailsDTO.getId()).get();
        return ResponseEntity.created(new URI("/api/duplicate-tb-guideline-details/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    @PostMapping("/create-common-activity-guideline-details/{activityTypeName}")
    @Transactional(readOnly = false)
    public ResponseEntity<Long> createCommonActivityGuidelineDetails(@PathVariable String activityTypeName,
                                                                                      @RequestBody TBCommonActivityGDDTO tbCommonActivityGDDTO) throws URISyntaxException {
        TBActivityTypeDTO tbActivityTypeDTO = tbActivityTypeService.findOne(tbCommonActivityGDDTO.getTbGuidelineActivityDTO().getTbActivityTypeId()).get();
        if(!tbActivityTypeDTO.getName().equals(activityTypeName)){
            throw new ForbiddenException();
        }
        Long result = tBGuidelineDetailsQueryService.createCommonActivityGuidelineDetails(tbCommonActivityGDDTO);
        return ResponseEntity.ok().body(result);
    }

    @GetMapping("/get-detail-common-activity-guideline-details/{activityTypeName}/{tbGuidelineActivityId}")
    @Timed
    public ResponseEntity<TBCommonActivityGDDTO> getDetailCommonActivityGuidelineDetails(@PathVariable String activityTypeName,
                                                                                         @PathVariable Long tbGuidelineActivityId) throws URISyntaxException {
        TBGuidelineActivityDTO tbGuidelineActivityDTO = tbGuidelineActivityService.findOne(tbGuidelineActivityId).get();
        if(!tbGuidelineActivityDTO.getActivityTypeName().equals(activityTypeName)){
            throw new ForbiddenException();
        }
        TBCommonActivityGDDTO result = tBGuidelineDetailsQueryService.getDetailCommonActivityGuidelineDetails(tbGuidelineActivityId);
        return ResponseEntity.ok().body(result);
    }

    @PostMapping("/update-common-activity-guideline-details/{activityTypeName}")
    @Transactional(readOnly = false)
    @Timed
    public ResponseEntity<Long> updateCommonActivityGuidelineDetails(@PathVariable String activityTypeName,
                                                                                      @RequestBody TBCommonActivityGDDTO tbCommonActivityGDDTO) throws URISyntaxException {
        TBActivityTypeDTO tbActivityTypeDTO = tbActivityTypeService.findOne(tbCommonActivityGDDTO.getTbGuidelineActivityDTO().getTbActivityTypeId()).get();
        if(!tbActivityTypeDTO.getName().equals(activityTypeName)){
            throw new ForbiddenException();
        }
        Long result = tBGuidelineDetailsQueryService.updateCommonActivityGuidelineDetails(tbCommonActivityGDDTO);
        return ResponseEntity.ok().body(result);
    }

    @DeleteMapping("/delete-common-activity-guideline-details/{activityTypeName}/{tbGuidelineActivityId}")
    @Transactional(readOnly = false)
    @Timed
    public ResponseEntity<Long> deleteCommonActivityGuidelineDetails(@PathVariable String activityTypeName,
                                                                     @PathVariable Long tbGuidelineActivityId) throws URISyntaxException {
        TBGuidelineActivityDTO tbGuidelineActivityDTO = tbGuidelineActivityService.findOne(tbGuidelineActivityId).get();
        if(!tbGuidelineActivityDTO.getActivityTypeName().equals(activityTypeName)){
            throw new ForbiddenException();
        }
        tBGuidelineDetailsQueryService.deleteCommonActivityGuidelineDetails(tbGuidelineActivityId);
        return ResponseEntity.ok().body(tbGuidelineActivityId);
    }

    @GetMapping("/get-all-common-activity-guideline-details/{tbGuidelineDetailsId}")
    @Transactional(readOnly = false)
    @Timed
    public ResponseEntity<List<TBGuidelineActivityDTO>> getAllCommonActivityGuidelineDetails(@PathVariable Long tbGuidelineDetailsId) throws URISyntaxException {
        TBGuidelineActivityCriteria guidelineDetailsCriteria = new TBGuidelineActivityCriteria();
        LongFilter guidelineDetailsIdFilter = new LongFilter();
        guidelineDetailsIdFilter.setEquals(tbGuidelineDetailsId);
        guidelineDetailsCriteria.setTbGuidelineDetailsId(guidelineDetailsIdFilter);
        List<TBGuidelineActivityDTO> tbGuidelineActivities = tbGuidelineActivityQueryService.findByCriteria(guidelineDetailsCriteria);
        return ResponseEntity.ok().body(tbGuidelineActivities);
    }
}
