package vn.azteam.tpf.service;

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

import javax.persistence.criteria.JoinType;

import com.google.common.collect.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.TBWard;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBWardRepository;
import vn.azteam.tpf.repository.search.TBWardSearchRepository;
import vn.azteam.tpf.service.dto.TBDistrictCriteria;
import vn.azteam.tpf.service.dto.TBDistrictDTO;
import vn.azteam.tpf.service.dto.TBWardCriteria;
import vn.azteam.tpf.service.dto.TBWardDTO;
import vn.azteam.tpf.service.mapper.TBWardMapper;

import static vn.azteam.tpf.web.rest.util.ConvertCharacterUtil.removeAccent;

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

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

    private final TBWardRepository tBWardRepository;

    private final TBWardMapper tBWardMapper;

    private final TBWardSearchRepository tBWardSearchRepository;

    public TBWardQueryService(TBWardRepository tBWardRepository, TBWardMapper tBWardMapper, TBWardSearchRepository tBWardSearchRepository) {
        this.tBWardRepository = tBWardRepository;
        this.tBWardMapper = tBWardMapper;
        this.tBWardSearchRepository = tBWardSearchRepository;
    }

    /**
     * Return a {@link List} of {@link TBWardDTO} 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<TBWardDTO> findByCriteria(TBWardCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBWard> specification = createSpecification(criteria);
        return tBWardMapper.toDto(tBWardRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBWardCriteria to a {@link Specification}
     */
    private Specification<TBWard> createSpecification(TBWardCriteria criteria) {
        Specification<TBWard> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBWard_.id));
            }
            if (criteria.getName() != null) {
                specification = specification.and(buildStringSpecification(criteria.getName(), TBWard_.name));
            }
            if (criteria.getTbDistrictId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbDistrictId(),
                    root -> root.join(TBWard_.tbDistrict, JoinType.LEFT).get(TBDistrict_.id)));
            }
        }
        return specification;
    }

    public Page<TBWardDTO> getTbWardsByDistrict(Long districtId, String query, TBWardCriteria criteria, Pageable page) {
        List<TBWard> listData =  tBWardRepository.findAll().stream()
            .filter(item -> item.getTbDistrict()!=null && item.getTbDistrict().getId().equals(districtId))
            .collect(Collectors.toList());

        if (query != null && !query.isEmpty()) {
            listData = listData.stream().filter(
                item -> queryContain(item.getName(), query)
            ).collect(Collectors.toList());
        }

        List<Long>listDataId = listData.stream().map(TBWard::getId).collect(Collectors.toList());
        if (listDataId.size() > 0) {
            LongFilter wardsId = new LongFilter();
            wardsId.setIn(listDataId);
            criteria.setId(wardsId);
            final Specification<TBWard> specification = createSpecification(criteria);
            Page<TBWardDTO> pages = tBWardRepository.findAll(specification, page)
                .map(tBWardMapper::toDto);
            return pages;
        } else {
            return new PageImpl<>(Lists.newArrayList(), page, 0);
        }
    }

    private Boolean queryContain(String data, String query) {
        if (data == null) {
            return Boolean.FALSE;
        } else {
            return removeAccent(data.toLowerCase()).contains(removeAccent(query.toLowerCase()));
        }
    }
}
