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.TBDistrict;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBDistrictRepository;
import vn.azteam.tpf.repository.search.TBDistrictSearchRepository;
import vn.azteam.tpf.service.dto.TBCityCriteria;
import vn.azteam.tpf.service.dto.TBCityDTO;
import vn.azteam.tpf.service.dto.TBDistrictCriteria;
import vn.azteam.tpf.service.dto.TBDistrictDTO;
import vn.azteam.tpf.service.mapper.TBDistrictMapper;

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

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

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

    private final TBDistrictRepository tBDistrictRepository;

    private final TBDistrictMapper tBDistrictMapper;

    private final TBDistrictSearchRepository tBDistrictSearchRepository;

    public TBDistrictQueryService(TBDistrictRepository tBDistrictRepository, TBDistrictMapper tBDistrictMapper, TBDistrictSearchRepository tBDistrictSearchRepository) {
        this.tBDistrictRepository = tBDistrictRepository;
        this.tBDistrictMapper = tBDistrictMapper;
        this.tBDistrictSearchRepository = tBDistrictSearchRepository;
    }

    /**
     * Return a {@link List} of {@link TBDistrictDTO} 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<TBDistrictDTO> findByCriteria(TBDistrictCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBDistrict> specification = createSpecification(criteria);
        return tBDistrictMapper.toDto(tBDistrictRepository.findAll(specification));
    }

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

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

    public Page<TBDistrictDTO> getTbDistrictByCity(Long cityId, String query, TBDistrictCriteria criteria, Pageable page) {
        List<TBDistrict> listData =  tBDistrictRepository.findAll().stream()
            .filter(item -> item.getTbCity().getId() == cityId)
            .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(TBDistrict::getId).collect(Collectors.toList());
        if (listDataId.size() > 0) {
            LongFilter districtId = new LongFilter();
            districtId.setIn(listDataId);
            criteria.setId(districtId);
            final Specification<TBDistrict> specification = createSpecification(criteria);
            Page<TBDistrictDTO> pages = tBDistrictRepository.findAll(specification, page)
                .map(tBDistrictMapper::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()));
        }
    }
}
