package vn.azteam.tpf.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.persistence.Table;
import javax.persistence.criteria.JoinType;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
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 io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.domain.TBGuidelinePeriod;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBGuidelinePeriodRepository;
import vn.azteam.tpf.repository.search.TBGuidelinePeriodSearchRepository;
import vn.azteam.tpf.service.dto.TBGuidelinePeriodCriteria;
import vn.azteam.tpf.service.dto.TBGuidelinePeriodDTO;
import vn.azteam.tpf.service.mapper.TBGuidelinePeriodMapper;

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

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

    private final TBGuidelinePeriodRepository tBGuidelinePeriodRepository;

    private final TBGuidelinePeriodMapper tBGuidelinePeriodMapper;

    private final TBGuidelinePeriodSearchRepository tBGuidelinePeriodSearchRepository;

    private final EntityManager em;

    public TBGuidelinePeriodQueryService(TBGuidelinePeriodRepository tBGuidelinePeriodRepository,
                                         TBGuidelinePeriodMapper tBGuidelinePeriodMapper,
                                         TBGuidelinePeriodSearchRepository tBGuidelinePeriodSearchRepository,
                                         EntityManager em) {
        this.tBGuidelinePeriodRepository = tBGuidelinePeriodRepository;
        this.tBGuidelinePeriodMapper = tBGuidelinePeriodMapper;
        this.tBGuidelinePeriodSearchRepository = tBGuidelinePeriodSearchRepository;
        this.em = em;
    }

    /**
     * Return a {@link List} of {@link TBGuidelinePeriodDTO} 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<TBGuidelinePeriodDTO> findByCriteria(TBGuidelinePeriodCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBGuidelinePeriod> specification = createSpecification(criteria);
        return tBGuidelinePeriodMapper.toDto(tBGuidelinePeriodRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBGuidelinePeriodCriteria to a {@link Specification}
     */
    private Specification<TBGuidelinePeriod> createSpecification(TBGuidelinePeriodCriteria criteria) {
        Specification<TBGuidelinePeriod> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBGuidelinePeriod_.id));
            }
            if (criteria.getName() != null) {
                specification = specification.and(buildStringSpecification(criteria.getName(), TBGuidelinePeriod_.name));
            }
            if (criteria.getAgeDayStart() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getAgeDayStart(), TBGuidelinePeriod_.ageDayStart));
            }
            if (criteria.getAgeDayEnd() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getAgeDayEnd(), TBGuidelinePeriod_.ageDayEnd));
            }
            if (criteria.getTbGuidelineId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbGuidelineId(),
                    root -> root.join(TBGuidelinePeriod_.tbGuideline, JoinType.LEFT).get(TBGuideline_.id)));
            }
        }
        return specification;
    }




    public List<TBGuidelinePeriodDTO> findByGuidelineId(Long guideLineId) {
        TBGuidelinePeriodCriteria criteria = new TBGuidelinePeriodCriteria();
        LongFilter guideLineIdFilter = new LongFilter();
        guideLineIdFilter.setEquals(guideLineId);
        criteria.setTbGuidelineId(guideLineIdFilter);
        return findByCriteria(criteria);
    }

    @Transactional(readOnly = true)
    public List<TBGuidelinePeriodDTO> findByCropId(Long cropId) {
        String query = "SELECT guideline_periods.* \n" +
        "FROM "+TBGuidelinePeriod.class.getAnnotation(Table.class).name()+" guideline_periods \n" +
        "INNER JOIN "+TBGuideline.class.getAnnotation(Table.class).name()+" as guideline on guideline_periods.tb_guideline_id = guideline.id \n" +
        "INNER JOIN "+TBCrop.class.getAnnotation(Table.class).name()+" as crop on crop.tb_guideline_id = guideline.id \n" +
        "WHERE crop.id = :cropId \n";
        Query nativeQuery = em.createNativeQuery(query, TBGuidelinePeriod.class);
        nativeQuery.setParameter("cropId", cropId);
        return tBGuidelinePeriodMapper.toDto(nativeQuery.getResultList());
    }
}
