package vn.azteam.tpf.service;

import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

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 io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.domain.TBBlockDetails;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBBlockDetailsRepository;
import vn.azteam.tpf.repository.search.TBBlockDetailsSearchRepository;
import vn.azteam.tpf.service.dto.TBBlockDetailsCriteria;
import vn.azteam.tpf.service.dto.TBBlockDetailsDTO;
import vn.azteam.tpf.service.dto.TBSuppliesInWarehouseDTO;
import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.service.mapper.TBBlockDetailsMapper;

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

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

    private final TBBlockDetailsRepository tBBlockDetailsRepository;

    private final TBBlockDetailsMapper tBBlockDetailsMapper;

    private final TBBlockDetailsSearchRepository tBBlockDetailsSearchRepository;

    private final UserService userService;

    public TBBlockDetailsQueryService(TBBlockDetailsRepository tBBlockDetailsRepository,
                                      TBBlockDetailsMapper tBBlockDetailsMapper,
                                      TBBlockDetailsSearchRepository tBBlockDetailsSearchRepository,
                                      UserService userService) {
        this.tBBlockDetailsRepository = tBBlockDetailsRepository;
        this.tBBlockDetailsMapper = tBBlockDetailsMapper;
        this.tBBlockDetailsSearchRepository = tBBlockDetailsSearchRepository;
        this.userService = userService;
    }

    /**
     * Return a {@link List} of {@link TBBlockDetailsDTO} 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<TBBlockDetailsDTO> findByCriteria(TBBlockDetailsCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBBlockDetails> specification = createSpecification(criteria);
        return tBBlockDetailsMapper.toDto(tBBlockDetailsRepository.findAll(specification));
    }

    /**
     * Return a {@link Page} of {@link TBBlockDetailsDTO} 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<TBBlockDetailsDTO> findByCriteria(TBBlockDetailsCriteria criteria, Pageable page) {
        log.debug("find by criteria : {}, page: {}", criteria, page);
        final Specification<TBBlockDetails> specification = createSpecification(criteria);
        return tBBlockDetailsRepository.findAll(specification, page)
            .map(tBBlockDetailsMapper::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(TBBlockDetailsCriteria criteria) {
        log.debug("count by criteria : {}", criteria);
        final Specification<TBBlockDetails> specification = createSpecification(criteria);
        return tBBlockDetailsRepository.count(specification);
    }

    /**
     * Function to convert TBBlockDetailsCriteria to a {@link Specification}
     */
    private Specification<TBBlockDetails> createSpecification(TBBlockDetailsCriteria criteria) {
        Specification<TBBlockDetails> specification = Specification.where(null);
        if (criteria != null) {
            UserDTO currentUser = userService.getCurrentUserDTO().get();

            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBBlockDetails_.id));
            }
            if (criteria.getQuantity() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getQuantity(), TBBlockDetails_.quantity));
            }
            if (criteria.getCode() != null) {
                specification = specification.and(buildStringSpecification(criteria.getCode(), TBBlockDetails_.code));
            }
            if (criteria.getMfgDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getMfgDate(), TBBlockDetails_.mfgDate));
            }
            if (criteria.getExpDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getExpDate(), TBBlockDetails_.expDate));
            }
            if (criteria.getTbSuppliesInWarehouseId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbSuppliesInWarehouseId(),
                    root -> root.join("tbSuppliesInWarehouse", JoinType.LEFT).get("id")));
            }
            if (criteria.getTbSuppliesId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbSuppliesId(),
                    root -> root.join("tbSuppliesInWarehouse", JoinType.LEFT).join("tbSupplies", JoinType.LEFT).get("id")));
            }
            if (criteria.getTbEntityId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbEntityId(),
                    root -> root.join("tbSuppliesInWarehouse", JoinType.LEFT).join("tbEntity", JoinType.LEFT).get("id")));
            }

            if(!userService.isAllCustomerRole(currentUser.getRoleId())) {
                LongFilter customerIdFilter = new LongFilter();
                customerIdFilter.setEquals(currentUser.getCustomerId());
                specification = specification.and(buildSpecification(customerIdFilter,
                root -> root.join("tbSuppliesInWarehouse", JoinType.LEFT)
                    .join("tbSupplies", JoinType.LEFT)
                    .join("tbCustomer", JoinType.LEFT).get("id")));

                specification = specification.and(buildSpecification(customerIdFilter,
                root -> root.join("tbSuppliesInWarehouse", JoinType.LEFT)
                    .join("tbEntity", JoinType.LEFT)
                    .join("tbCustomer", JoinType.LEFT).get("id")));
            }
        }
        return specification;
    }
}
