package vn.azteam.tpf.service;

import java.util.List;

import javax.persistence.Query;
import javax.persistence.criteria.JoinType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import io.github.jhipster.service.QueryService;

import vn.azteam.tpf.domain.TBNotification;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBNotificationRepository;
import vn.azteam.tpf.repository.search.TBNotificationSearchRepository;
import vn.azteam.tpf.service.dto.TBNotificationCriteria;
import vn.azteam.tpf.service.dto.TBNotificationDTO;
import vn.azteam.tpf.service.mapper.TBNotificationMapper;

import javax.persistence.EntityManager;
/**
 * Service for executing complex queries for TBNotification entities in the database.
 * The main input is a {@link TBNotificationCriteria} which gets converted to {@link Specification},
 * in a way that all the filters must apply.
 * It returns a {@link List} of {@link TBNotificationDTO} or a {@link Page} of {@link TBNotificationDTO} which fulfills the criteria.
 */
@Service
@Transactional(readOnly = true)
public class TBNotificationQueryService extends QueryService<TBNotification> {

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

    private final TBNotificationRepository tBNotificationRepository;

    private final TBNotificationMapper tBNotificationMapper;

    private final TBNotificationSearchRepository tBNotificationSearchRepository;

    private final EntityManager entityManager;

    public TBNotificationQueryService(TBNotificationRepository tBNotificationRepository,
                                      TBNotificationMapper tBNotificationMapper,
                                      EntityManager entityManager,
                                      TBNotificationSearchRepository tBNotificationSearchRepository) {
        this.tBNotificationRepository = tBNotificationRepository;
        this.tBNotificationMapper = tBNotificationMapper;
        this.tBNotificationSearchRepository = tBNotificationSearchRepository;
        this.entityManager = entityManager;
    }

    /**
     * Return a {@link List} of {@link TBNotificationDTO} which matches the criteria from the database
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the matching entities.
     */
    @Transactional(readOnly = true)
    public List<TBNotificationDTO> findByCriteria(TBNotificationCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBNotification> specification = createSpecification(criteria);
        return tBNotificationMapper.toDto(tBNotificationRepository.findAll(specification));
    }

    /**
     * Return a {@link Page} of {@link TBNotificationDTO} which matches the criteria from the database
     * @param criteria The object which holds all the filters, which the entities should match.
     * @param page The page, which should be returned.
     * @return the matching entities.
     */
    @Transactional(readOnly = true)
    public Page<TBNotificationDTO> findByCriteria(TBNotificationCriteria criteria, Pageable page) {
        log.debug("find by criteria : {}, page: {}", criteria, page);
        final Specification<TBNotification> specification = createSpecification(criteria);
        return tBNotificationRepository.findAll(specification, page)
            .map(tBNotificationMapper::toDto);
    }

    /**
     * Return the number of matching entities in the database
     * @param criteria The object which holds all the filters, which the entities should match.
     * @return the number of matching entities.
     */
    @Transactional(readOnly = true)
    public long countByCriteria(TBNotificationCriteria criteria) {
        log.debug("count by criteria : {}", criteria);
        final Specification<TBNotification> specification = createSpecification(criteria);
        return tBNotificationRepository.count(specification);
    }

    /**
     * Function to convert TBNotificationCriteria to a {@link Specification}
     */
    private Specification<TBNotification> createSpecification(TBNotificationCriteria criteria) {
        Specification<TBNotification> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBNotification_.id));
            }
            if (criteria.getChannel() != null) {
                specification = specification.and(buildStringSpecification(criteria.getChannel(), TBNotification_.channel));
            }
            if (criteria.getSendFrom() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getSendFrom(), TBNotification_.sendFrom));
            }
            if (criteria.getSendTo() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getSendTo(), TBNotification_.sendTo));
            }
            if (criteria.getSubject() != null) {
                specification = specification.and(buildStringSpecification(criteria.getSubject(), TBNotification_.subject));
            }
            if (criteria.getMessage() != null) {
                specification = specification.and(buildStringSpecification(criteria.getMessage(), TBNotification_.message));
            }
            if (criteria.getStatus() != null) {
                specification = specification.and(buildStringSpecification(criteria.getStatus(), TBNotification_.status));
            }
            if (criteria.getTbCropId() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getTbCropId(), TBNotification_.tbCropId));
            }
            if (criteria.getTbEntityId() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getTbEntityId(), TBNotification_.tbEntityId));
            }
            if (criteria.getClickAction() != null) {
                specification = specification.and(buildStringSpecification(criteria.getClickAction(), TBNotification_.clickAction));
            }
            if (criteria.getContents() != null) {
                specification = specification.and(buildStringSpecification(criteria.getContents(), TBNotification_.contents));
            }
            if (criteria.getCreatedDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getCreatedDate(), TBNotification_.createdDate));
            }
            if (criteria.getSendDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getSendDate(), TBNotification_.sendDate));
            }
            if (criteria.getIsRead() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getIsRead(), TBNotification_.isRead));
            }
            if (criteria.getIsTestMessage() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getIsTestMessage(), TBNotification_.isTestMessage));
            }
            if (criteria.getType() != null) {
                specification = specification.and(buildStringSpecification(criteria.getType(), TBNotification_.type));
            }
            if (criteria.getExternalId() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getExternalId(), TBNotification_.externalId));
            }
        }
        return specification;
    }

    public Integer getTotalNumberByCurrentUser(Long sendTo, Integer isRead) {
        Query totalNumberQuery = entityManager.createNativeQuery(
            String.format("Select tbl.*\n" +
                "FROM `tb_notification` AS tbl\n" +
                "WHERE tbl.is_read = :isRead AND tbl.send_to = :sendTo\n"),TBNotification.class);
        totalNumberQuery.setParameter("isRead", isRead);
        totalNumberQuery.setParameter("sendTo", sendTo);
        return totalNumberQuery.getResultList().size();
    }
}
