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.TBCountry;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBCountryRepository;
import vn.azteam.tpf.repository.search.TBCountrySearchRepository;
import vn.azteam.tpf.service.dto.TBCountryCriteria;
import vn.azteam.tpf.service.dto.TBCountryDTO;
import vn.azteam.tpf.service.dto.TBWardCriteria;
import vn.azteam.tpf.service.dto.TBWardDTO;
import vn.azteam.tpf.service.mapper.TBCountryMapper;

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

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

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

    private final TBCountryRepository tBCountryRepository;

    private final TBCountryMapper tBCountryMapper;

    private final TBCountrySearchRepository tBCountrySearchRepository;

    public TBCountryQueryService(TBCountryRepository tBCountryRepository, TBCountryMapper tBCountryMapper, TBCountrySearchRepository tBCountrySearchRepository) {
        this.tBCountryRepository = tBCountryRepository;
        this.tBCountryMapper = tBCountryMapper;
        this.tBCountrySearchRepository = tBCountrySearchRepository;
    }

    /**
     * Return a {@link List} of {@link TBCountryDTO} 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<TBCountryDTO> findByCriteria(TBCountryCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBCountry> specification = createSpecification(criteria);
        return tBCountryMapper.toDto(tBCountryRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBCountryCriteria to a {@link Specification}
     */
    private Specification<TBCountry> createSpecification(TBCountryCriteria criteria) {
        Specification<TBCountry> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBCountry_.id));
            }
            if (criteria.getName() != null) {
                specification = specification.and(buildStringSpecification(criteria.getName(), TBCountry_.name));
            }
        }
        return specification;
    }


    public Page<TBCountryDTO> getTBCountries(String query, TBCountryCriteria criteria, Pageable page) {
        List<TBCountry> listData =  tBCountryRepository.findAll();

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

        List<Long>listDataId = listData.stream().map(TBCountry::getId).collect(Collectors.toList());
        if (listDataId.size() > 0) {
            LongFilter wardsId = new LongFilter();
            wardsId.setIn(listDataId);
            criteria.setId(wardsId);
            final Specification<TBCountry> specification = createSpecification(criteria);
            Page<TBCountryDTO> pages = tBCountryRepository.findAll(specification, page)
                .map(tBCountryMapper::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()));
        }
    }
}
