package vn.azteam.tpf.service;

import java.util.List;
import java.util.Optional;

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.TBProductStockUpdate;
import vn.azteam.tpf.Constants.Constants.PRODUCT_STOCK_UPDATE_ACTION;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBProductStockUpdateRepository;
import vn.azteam.tpf.repository.search.TBProductStockUpdateSearchRepository;
import vn.azteam.tpf.service.dto.TBProductStockUpdateCriteria;
import vn.azteam.tpf.service.dto.TBProductStockUpdateDTO;
import vn.azteam.tpf.service.mapper.TBProductStockUpdateMapper;

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

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

    private final TBProductStockUpdateRepository tBProductStockUpdateRepository;

    private final TBProductStockUpdateMapper tBProductStockUpdateMapper;

    private final TBProductStockUpdateSearchRepository tBProductStockUpdateSearchRepository;

    private final EntityManager em;

    public TBProductStockUpdateQueryService(TBProductStockUpdateRepository tBProductStockUpdateRepository,
                                            TBProductStockUpdateMapper tBProductStockUpdateMapper,
                                            TBProductStockUpdateSearchRepository tBProductStockUpdateSearchRepository,
                                            EntityManager em) {
        this.tBProductStockUpdateRepository = tBProductStockUpdateRepository;
        this.tBProductStockUpdateMapper = tBProductStockUpdateMapper;
        this.tBProductStockUpdateSearchRepository = tBProductStockUpdateSearchRepository;
        this.em = em;
    }

    /**
     * Return a {@link List} of {@link TBProductStockUpdateDTO} 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<TBProductStockUpdateDTO> findByCriteria(TBProductStockUpdateCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBProductStockUpdate> specification = createSpecification(criteria);
        return tBProductStockUpdateMapper.toDto(tBProductStockUpdateRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBProductStockUpdateCriteria to a {@link Specification}
     */
    private Specification<TBProductStockUpdate> createSpecification(TBProductStockUpdateCriteria criteria) {
        Specification<TBProductStockUpdate> specification = Specification.where(null);
        if (criteria != null) {
            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBProductStockUpdate_.id));
            }
            if (criteria.getUpdateDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getUpdateDate(), TBProductStockUpdate_.updateDate));
            }
            if (criteria.getAction() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getAction(), TBProductStockUpdate_.action));
            }
            if (criteria.getQuantity() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getQuantity(), TBProductStockUpdate_.quantity));
            }
            if (criteria.getDescription() != null) {
                specification = specification.and(buildStringSpecification(criteria.getDescription(), TBProductStockUpdate_.description));
            }
            if (criteria.getUpdateBy() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getUpdateBy(), TBProductStockUpdate_.updateBy));
            }
            if (criteria.getTbProductBlockDetailsId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbProductBlockDetailsId(),
                    root -> root.join(TBProductStockUpdate_.tbProductBlockDetails, JoinType.LEFT).get(TBProductBlockDetails_.id)));
            }
            if (criteria.getTbActivityId() != null) {
                specification = specification.and(buildSpecification(criteria.getTbActivityId(),
                    root -> root.join(TBProductStockUpdate_.tbActivity, JoinType.LEFT).get(TBActivity_.id)));
            }
        }
        return specification;
    }

    /**
     * Get import action stock update
     * @param id
     * @return
     */
    public TBProductStockUpdateDTO findImportActionOneByBlockId(Long id) {
        String query = "SELECT * \n" +
        "FROM "+TBProductStockUpdate.class.getAnnotation(Table.class).name()+" psu \n" +
        "WHERE psu.action = :action \n" + 
        "AND psu.tb_product_block_details_id = :blockId \n";
        
        Query nativeQuery = em.createNativeQuery(query ,TBProductStockUpdate.class);
        nativeQuery.setParameter("action", PRODUCT_STOCK_UPDATE_ACTION.IMPORT.getValue());
        nativeQuery.setParameter("blockId", id);

        return tBProductStockUpdateMapper.toDto((TBProductStockUpdate) nativeQuery.getSingleResult());
    }
}
