package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.service.TBNotificationService;
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.TBNotificationDTO;
import vn.azteam.tpf.service.dto.TBNotificationCriteria;
import vn.azteam.tpf.service.TBNotificationQueryService;
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.dto.NotificationBellDTO;
import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.service.UserService;
import vn.azteam.tpf.service.dto.UpdateAllNotificationDTO;
import vn.azteam.tpf.service.util.UserRoleUtil;
//import vn.azteam.tpf.service.dto;

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

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

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

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

    private static final String ENTITY_NAME = "tBNotification";

    private final TBNotificationService tBNotificationService;

    private final UserService userService;

    private final UserRoleUtil userRoleUtil;

    private final TBNotificationQueryService tBNotificationQueryService;

    private final PageableUtil pageableUtil;

    public TBNotificationResource(TBNotificationService tBNotificationService,
                                  UserService userService,
                                  UserRoleUtil userRoleUtil,
                                  TBNotificationQueryService tBNotificationQueryService, PageableUtil pageableUtil) {
        this.tBNotificationService = tBNotificationService;
        this.userService = userService;
        this.userRoleUtil = userRoleUtil;
        this.tBNotificationQueryService = tBNotificationQueryService;
        this.pageableUtil = pageableUtil;
    }

    /**
     * POST  /tb-notifications : Create a new tBNotification.
     *
     * @param tBNotificationDTO the tBNotificationDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBNotificationDTO, or with status 400 (Bad Request) if the tBNotification has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-notifications")
    @Timed
    public ResponseEntity<TBNotificationDTO> createTBNotification(@RequestBody TBNotificationDTO tBNotificationDTO) throws URISyntaxException {
        log.debug("REST request to save TBNotification : {}", tBNotificationDTO);
        if (tBNotificationDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBNotification cannot already have an ID", ENTITY_NAME, "idexists");
        }
        //@CUONGLT - Filter scope customer's data
        if(!userRoleUtil.currentUserHasPermissionByCropId(tBNotificationDTO.getTbCropId())){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }
        TBNotificationDTO result = tBNotificationService.save(tBNotificationDTO);
        return ResponseEntity.created(new URI("/api/tb-notifications/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tb-notifications : Updates an existing tBNotification.
     *
     * @param tBNotificationDTO the tBNotificationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBNotificationDTO,
     * or with status 400 (Bad Request) if the tBNotificationDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBNotificationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-notifications")
    @Timed
    public ResponseEntity<TBNotificationDTO> updateTBNotification(@RequestBody TBNotificationDTO tBNotificationDTO) throws URISyntaxException {
        log.debug("REST request to update TBNotification : {}", tBNotificationDTO);
        if (tBNotificationDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        //@CUONGLT - Filter scope customer's data
        if(!userRoleUtil.currentUserHasPermissionByCropId(tBNotificationDTO.getTbCropId())){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }
        TBNotificationDTO result = tBNotificationService.save(tBNotificationDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBNotificationDTO.getId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-notifications : get all the tBNotifications.
     *
     * @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 tBNotifications in body
     */
    @GetMapping("/tb-notifications")
    @Timed
    public ResponseEntity<List<TBNotificationDTO>> getAllTBNotifications(TBNotificationCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBNotifications by criteria: {}", criteria);
        Page<TBNotificationDTO> page = tBNotificationQueryService.findByCriteria(criteria, pageable);
        List<TBNotificationDTO> tbNotificationDTOList = page.getContent().stream()
            .filter(notify -> userRoleUtil.currentUserHasPermissionByCropId(notify.getTbCropId()))
            .collect(Collectors.toList());
        page = pageableUtil.changeTBNotificationDTOToPageFromList(tbNotificationDTOList,pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-notifications");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

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

    /**
     * GET  /tb-notifications/:id : get the "id" tBNotification.
     *
     * @param id the id of the tBNotificationDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBNotificationDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-notifications/{id}")
    @Timed
    public ResponseEntity<TBNotificationDTO> getTBNotification(@PathVariable Long id) {
        log.debug("REST request to get TBNotification : {}", id);
        Optional<TBNotificationDTO> tBNotificationDTO = tBNotificationService.findOne(id);
        //@CUONGLT - Filter scope customer's data
        if(!userRoleUtil.currentUserHasPermissionByCropId(tBNotificationDTO.get().getTbCropId())){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }
        return ResponseUtil.wrapOrNotFound(tBNotificationDTO);
    }

    /**
     * DELETE  /tb-notifications/:id : delete the "id" tBNotification.
     *
     * @param id the id of the tBNotificationDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-notifications/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBNotification(@PathVariable Long id) {
        log.debug("REST request to delete TBNotification : {}", id);
        TBNotificationDTO tbNotificationDTO = tBNotificationService.findOne(id).get();
        //@CUONGLT - Filter scope customer's data
        if(!userRoleUtil.currentUserHasPermissionByCropId(tbNotificationDTO.getTbCropId())){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }
        tBNotificationService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-notifications?query=:query : search for the tBNotification corresponding
     * to the query.
     *
     * @param query the query of the tBNotification search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-notifications")
    @Timed
    public ResponseEntity<List<TBNotificationDTO>> searchTBNotifications(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBNotifications for query {}", query);
        Page<TBNotificationDTO> page = tBNotificationService.search(query, pageable);
        List<TBNotificationDTO> tbNotificationDTOList = page.getContent().stream()
            .filter(notify -> userRoleUtil.currentUserHasPermissionByCropId(notify.getTbCropId()))
            .collect(Collectors.toList());
        page = pageableUtil.changeTBNotificationDTOToPageFromList(tbNotificationDTOList,pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-notifications");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    /**
     * PUT  /notifications : Updates an existing notification.
     *
     * @param notificationDTO the notificationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated notificationDTO,
     * or with status 400 (Bad Request) if the notificationDTO is not valid,
     * or with status 500 (Internal Server Error) if the notificationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/notifications/update")
    @Timed
    public ResponseEntity<TBNotificationDTO> updateNotificationRead(@RequestBody TBNotificationDTO notificationDTO) throws URISyntaxException {
        log.debug("REST request to update Notification : {}", notificationDTO);
        if (notificationDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        TBNotificationDTO notificationDTODB = tBNotificationService.findOne(notificationDTO.getId()).get();

        //@CUONGLT - Filter scope customer's data
        if(!userRoleUtil.currentUserHasPermissionByCropId(notificationDTODB.getTbCropId())){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }

        notificationDTODB.setIsRead(notificationDTO.getIsRead());
        TBNotificationDTO result = tBNotificationService.save(notificationDTODB);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, notificationDTODB.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /notifications : Updates an existing notification.
     *
     * @param updateAllNotificationDTO the notificationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated notificationDTO,
     * or with status 400 (Bad Request) if the notificationDTO is not valid,
     * or with status 500 (Internal Server Error) if the notificationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/notifications/update-list")
    @Timed
    public ResponseEntity<List<TBNotificationDTO>> updateListNotification(@RequestBody UpdateAllNotificationDTO updateAllNotificationDTO) throws URISyntaxException {
        log.debug("REST request to update Notification : {}", updateAllNotificationDTO);
        List<TBNotificationDTO> tbNotificationDTOS = new ArrayList<>();
        for(Long id : updateAllNotificationDTO.getIds()) {
            TBNotificationDTO tbNotificationDTODB = tBNotificationService.findOne(id).get();
            //@CUONGLT - Filter scope customer's data
            if(userRoleUtil.currentUserHasPermissionByCropId(tbNotificationDTODB.getTbCropId())){
                tbNotificationDTODB.setIsRead(updateAllNotificationDTO.getIsRead());
                TBNotificationDTO result = tBNotificationService.save(tbNotificationDTODB);
                tbNotificationDTOS.add(result);
            }
        }
        if(tbNotificationDTOS.size() <= 0){
            throw new BadRequestAlertException("1018", ENTITY_NAME, "1018");
        }
        return ResponseEntity.ok().headers(null).body(tbNotificationDTOS);
    }

    /**
     * PUT  /notifications : Updates an existing notification.
     *
     * @param isRead the notificationDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated notificationDTO,
     * or with status 400 (Bad Request) if the notificationDTO is not valid,
     * or with status 500 (Internal Server Error) if the notificationDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/notifications/update-all")
    @Timed
    public ResponseEntity<List<TBNotificationDTO>> updateAllNotification(@RequestBody Integer isRead) throws URISyntaxException {
        UserDTO userDTO = userService.getCurrentUserDTO().get();
        TBNotificationCriteria tbNotificationCriteria = new TBNotificationCriteria();
        LongFilter sendToFilter = new LongFilter();
        sendToFilter.setEquals(userDTO.getId());
        tbNotificationCriteria.setSendTo(sendToFilter);

        IntegerFilter isReadFilter = new IntegerFilter();

        if(isRead == 1) {
            isReadFilter.setEquals(0);
        }
        else {
            isReadFilter.setEquals(1);
        }
        tbNotificationCriteria.setIsRead(isReadFilter);

        List<TBNotificationDTO> tbNotificationDTOS = tBNotificationQueryService.findByCriteria(tbNotificationCriteria);

        List<TBNotificationDTO> newNotificationDTOs = new ArrayList<>();
        for(TBNotificationDTO tbNotificationDTO: tbNotificationDTOS) {
            TBNotificationDTO tbNotificationDTODB = tBNotificationService.findOne(tbNotificationDTO.getId()).get();
            tbNotificationDTODB.setIsRead(isRead);
            TBNotificationDTO result = tBNotificationService.save(tbNotificationDTODB);
            newNotificationDTOs.add(result);
        }
        return ResponseEntity.ok().headers(null).body(newNotificationDTOs);
    }

    /**
     * GET  /notifications : get all the notifications by current user.
     *
     * @param pageable the pagination information
     * @return the ResponseEntity with status 200 (OK) and the list of notifications in body
     */
    @GetMapping("/notifications-current-user")
    @Timed
    public ResponseEntity<NotificationBellDTO> getAllNotificationsByCurrentUser(Pageable pageable) {
        //Get current user
        UserDTO currentUser = userService.getCurrentUserDTO().get();

        TBNotificationCriteria criteria = new TBNotificationCriteria();
        LongFilter userCriteria = new LongFilter();
        userCriteria.setEquals(currentUser.getId());
        criteria.setSendTo(userCriteria);

        Page<TBNotificationDTO> page = tBNotificationQueryService.findByCriteria(criteria, pageable);

        List<TBNotificationDTO> tbNotificationDTOList = page.getContent();
//            .stream()
//            .filter(notify -> userRoleUtil.currentUserHasPermissionByCropId(notify.getTbCropId()))
//            .collect(Collectors.toList());

        NotificationBellDTO notificationBellDTO = new NotificationBellDTO();
        notificationBellDTO.setTBNotificationDTOs(tbNotificationDTOList);

        Integer numberUnreadPage = page.getContent().stream()
            .filter(item -> item.getIsRead().equals(0))
            .collect(Collectors.toList()).size();
        notificationBellDTO.setNumberUnreadPage(numberUnreadPage);

        Integer numberReadPage = page.getContent().stream()
            .filter(item -> item.getIsRead().equals(1))
            .collect(Collectors.toList()).size();
        notificationBellDTO.setNumberReadPage(numberReadPage);

        notificationBellDTO.setNumberUnreadTotal(tBNotificationQueryService.getTotalNumberByCurrentUser(currentUser.getId(), 0));
        notificationBellDTO.setNumberReadTotal(tBNotificationQueryService.getTotalNumberByCurrentUser(currentUser.getId(), 1));

        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/notifications");
        return ResponseEntity.ok().headers(headers).body(notificationBellDTO);
    }
}
