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.TBCity;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBCityRepository;
import vn.azteam.tpf.repository.search.TBCitySearchRepository;
import vn.azteam.tpf.service.dto.*;
import vn.azteam.tpf.service.mapper.TBCityMapper;

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

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

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

    private final TBCityRepository tBCityRepository;

    private final TBCityMapper tBCityMapper;

    private final TBCitySearchRepository tBCitySearchRepository;

    public TBCityQueryService(TBCityRepository tBCityRepository, TBCityMapper tBCityMapper, TBCitySearchRepository tBCitySearchRepository) {
        this.tBCityRepository = tBCityRepository;
        this.tBCityMapper = tBCityMapper;
        this.tBCitySearchRepository = tBCitySearchRepository;
    }

    /**
     * Return a {@link List} of {@link TBCityDTO} 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<TBCityDTO> findByCriteria(TBCityCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBCity> specification = createSpecification(criteria);
        return tBCityMapper.toDto(tBCityRepository.findAll(specification));
    }

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

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

    public Page<TBCityDTO> getTbCityByCountry(Long countryId, String query, TBCityCriteria criteria, Pageable page) {
        List<TBCity> listData =  tBCityRepository.findAll().stream()
            .filter(item -> item.getTbCountry().getId() == countryId)
            .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(TBCity::getId).collect(Collectors.toList());
        if (listDataId.size() > 0) {
            LongFilter cityId = new LongFilter();
            cityId.setIn(listDataId);
            criteria.setId(cityId);
            final Specification<TBCity> specification = createSpecification(criteria);
            Page<TBCityDTO> pages = tBCityRepository.findAll(specification, page)
                .map(tBCityMapper::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()));
        }
    }
}
