package vn.azteam.tpf.service;

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

import javax.persistence.criteria.JoinType;

import com.google.api.client.util.Lists;
import io.github.jhipster.service.filter.LongFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
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.TBEquipmentHistory;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBEquipmentHistoryRepository;
import vn.azteam.tpf.repository.search.TBEquipmentHistorySearchRepository;
import vn.azteam.tpf.service.dto.TBEquipmentHistoryCriteria;
import vn.azteam.tpf.service.dto.TBEquipmentHistoryDTO;
import vn.azteam.tpf.service.mapper.TBEquipmentHistoryMapper;

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

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

    private final TBEquipmentHistoryRepository tBEquipmentHistoryRepository;

    private final TBEquipmentHistoryMapper tBEquipmentHistoryMapper;

    private final TBEquipmentHistorySearchRepository tBEquipmentHistorySearchRepository;

    public TBEquipmentHistoryQueryService(TBEquipmentHistoryRepository tBEquipmentHistoryRepository, TBEquipmentHistoryMapper tBEquipmentHistoryMapper, TBEquipmentHistorySearchRepository tBEquipmentHistorySearchRepository) {
        this.tBEquipmentHistoryRepository = tBEquipmentHistoryRepository;
        this.tBEquipmentHistoryMapper = tBEquipmentHistoryMapper;
        this.tBEquipmentHistorySearchRepository = tBEquipmentHistorySearchRepository;
    }

    /**
     * Return a {@link List} of {@link TBEquipmentHistoryDTO} 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<TBEquipmentHistoryDTO> findByCriteria(TBEquipmentHistoryCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBEquipmentHistory> specification = createSpecification(criteria);
        return tBEquipmentHistoryMapper.toDto(tBEquipmentHistoryRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBEquipmentHistoryCriteria to a {@link Specification}
     */
    private Specification<TBEquipmentHistory> createSpecification(TBEquipmentHistoryCriteria criteria) {
        Specification<TBEquipmentHistory> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBEquipmentHistory_.id));
            }
            if (criteria.getEvent() != null) {
                specification = specification.and(buildStringSpecification(criteria.getEvent(), TBEquipmentHistory_.event));
            }
            if (criteria.getDateOccurred() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getDateOccurred(), TBEquipmentHistory_.dateOccurred));
            }
            if (criteria.getStatus() != null) {
                specification = specification.and(buildSpecification(criteria.getStatus(), TBEquipmentHistory_.status));
            }
            if (criteria.getTbCommandId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbCommandId(),
                    root -> root.join(TBEquipmentHistory_.tbCommand, JoinType.LEFT).get(TBCommand_.id)));
            }
            if (criteria.getTbDetailUserId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbDetailUserId(),
                    root -> root.join(TBEquipmentHistory_.tbDetailUser, JoinType.LEFT).get(TBDetailUser_.id)));
            }
            if (criteria.getTbEquipmentOfCustomerId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbEquipmentOfCustomerId(),
                    root -> root.join(TBEquipmentHistory_.tbEquipmentOfCustomer, JoinType.LEFT).get(TBEquipmentOfCustomer_.id)));
            }
        }
        return specification;
    }

    public Page<TBEquipmentHistoryDTO> getTBEquipmentHistories(TBEquipmentHistoryCriteria criteria, Pageable page,
                                                               Instant startTime, Instant endTime, Long equipmentInWarehouseId) {
        List<TBEquipmentHistory> data = tBEquipmentHistoryRepository.findAll().stream().filter(item ->
            item.getTbEquipmentOfCustomer() != null
                && item.getTbEquipmentOfCustomer().getDeletedDate() == null
                && item.getTbEquipmentOfCustomer().getDeletedBy() == null
        ).collect(Collectors.toList());
        if (startTime != null && !startTime.toString().equals("")) {
            data = data.stream().filter(item ->
                item.getDateOccurred() != null && item.getDateOccurred().compareTo(startTime) >= 0
            ).collect(Collectors.toList());
        }
        if (endTime != null && !endTime.toString().equals("")) {
            data = data.stream().filter(item ->
                item.getDateOccurred() != null && item.getDateOccurred().compareTo(endTime) <= 0
            ).collect(Collectors.toList());
        }
        if (equipmentInWarehouseId != null){
            data =data.stream().filter(item->
                item.getTbEquipmentOfCustomer()!= null && item.getTbEquipmentOfCustomer().getId()==equipmentInWarehouseId
                ).collect(Collectors.toList());
        }
        List<Long> ids = data.stream().map(TBEquipmentHistory::getId).collect(Collectors.toList());
        if (ids.size() > 0) {
            LongFilter idFilter = new LongFilter();
            idFilter.setIn(ids);
            criteria.setId(idFilter);
            final Specification<TBEquipmentHistory> specification = createSpecification(criteria);
            return tBEquipmentHistoryRepository.findAll(specification, page)
                .map(tBEquipmentHistoryMapper::toDto);
        } else {
            return new PageImpl<>(Lists.newArrayList(), page, 0);
        }
    }
}
