package vn.azteam.tpf.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

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

import com.google.common.collect.Lists;
import io.github.jhipster.service.filter.InstantFilter;
import io.github.jhipster.service.filter.LongFilter;
import io.github.jhipster.service.filter.StringFilter;
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.Propagation;
import org.springframework.transaction.annotation.Transactional;

import io.github.jhipster.service.QueryService;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import vn.azteam.tpf.Constants.Constants;
import vn.azteam.tpf.domain.TBActivityType;
import vn.azteam.tpf.domain.*; // for static metamodels
import vn.azteam.tpf.repository.TBActivityTypeRepository;
import vn.azteam.tpf.service.dto.*;
import vn.azteam.tpf.service.mapper.TBActivityTypeMapper;

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

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

    private static final String ENTITY_NAME = "tBActivityType";

    private final TBActivityTypeRepository tBActivityTypeRepository;

    private final TBActivityTypeMapper tBActivityTypeMapper;

    private final TBActivityTypeService tBActivityTypeService;

    private final UserService userService;

    private final TBCustomerHasCropTypeQueryService tBCustomerHasCropTypeQueryService;

    private final FileStorageService fileStorageService;

    private final EntityManager em;

    private final TBControlTypeService tbControlTypeService;

    private final TBActivityExtendTypeService tbActivityExtendTypeService;

    private final TBObjectParameterService tbObjectParameterService;

    public TBActivityTypeQueryService(TBActivityTypeRepository tBActivityTypeRepository,
                                      TBActivityTypeMapper tBActivityTypeMapper,
                                      TBActivityTypeService tBActivityTypeService,
                                      UserService userService,
                                      TBCustomerHasCropTypeQueryService tBCustomerHasCropTypeQueryService,
                                      FileStorageService fileStorageService,
                                      EntityManager em,
                                      TBControlTypeService tbControlTypeService,
                                      TBActivityExtendTypeService tbActivityExtendTypeService,
                                      TBObjectParameterService tbObjectParameterService) {
        this.tBActivityTypeRepository = tBActivityTypeRepository;
        this.tBActivityTypeMapper = tBActivityTypeMapper;
        this.tBActivityTypeService = tBActivityTypeService;
        this.userService = userService;
        this.tBCustomerHasCropTypeQueryService = tBCustomerHasCropTypeQueryService;
        this.fileStorageService = fileStorageService;
        this.em = em;
        this.tbControlTypeService = tbControlTypeService;
        this.tbActivityExtendTypeService = tbActivityExtendTypeService;
        this.tbObjectParameterService = tbObjectParameterService;
    }

    /**
     * Return a {@link List} of {@link TBActivityTypeDTO} 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<TBActivityTypeDTO> findByCriteria(TBActivityTypeCriteria criteria) {
        log.debug("find by criteria : {}", criteria);
        final Specification<TBActivityType> specification = createSpecification(criteria);
        return tBActivityTypeMapper.toDto(tBActivityTypeRepository.findAll(specification));
    }

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

    /**
     * Function to convert TBActivityTypeCriteria to a {@link Specification}
     */
    private Specification<TBActivityType> createSpecification(TBActivityTypeCriteria criteria) {
        Specification<TBActivityType> specification = Specification.where(null);
        if (criteria != null) {
            UserDTO currentUser = userService.getCurrentUserDTO().get();

            if (criteria.getId() != null) {
                specification = specification.and(buildSpecification(criteria.getId(), TBActivityType_.id));
            }
            if (criteria.getName() != null) {
                specification = specification.and(buildStringSpecification(criteria.getName(), TBActivityType_.name));
            }
            if (criteria.getDescription() != null) {
                specification = specification.and(buildStringSpecification(criteria.getDescription(), TBActivityType_.description));
            }
            if (criteria.getIsCanDelete() != null) {
                specification = specification.and(buildSpecification(criteria.getIsCanDelete(), TBActivityType_.isCanDelete));
            }
            if (criteria.getUrlLogo() != null) {
                specification = specification.and(buildStringSpecification(criteria.getUrlLogo(), TBActivityType_.urlLogo));
            }
            if (criteria.getCreatedDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getCreatedDate(), TBActivityType_.createdDate));
            }
            if (criteria.getModifiedDate() != null) {
                specification = specification.and(buildRangeSpecification(criteria.getModifiedDate(), TBActivityType_.modifiedDate));
            }
//            if (criteria.getDeletedDate() != null) {
//                specification = specification.and(buildRangeSpecification(criteria.getDeletedDate(), TBActivityType_.deletedDate));
//            }
            //Filter deletedDate == null
            InstantFilter instantFilter = new InstantFilter();
            instantFilter.setSpecified(criteria.getDeletedDate() != null);
            criteria.setDeletedDate(instantFilter);
            specification = specification.and(buildRangeSpecification(criteria.getDeletedDate(), TBActivityType_.deletedDate));

            if (criteria.getDeletedById() != null) {
                specification = specification.and(buildSpecification(criteria.getDeletedById(),
                    root -> root.join(TBActivityType_.deletedBy, JoinType.LEFT).get(TBDetailUser_.id)));
            }
            if (criteria.getCreatedById() != null) {
                specification = specification.and(buildSpecification(criteria.getCreatedById(),
                    root -> root.join(TBActivityType_.createdBy, JoinType.LEFT).get(TBDetailUser_.id)));
            }
            if (criteria.getModifiedById() != null) {
                specification = specification.and(buildSpecification(criteria.getModifiedById(),
                    root -> root.join(TBActivityType_.modifiedBy, JoinType.LEFT).get(TBDetailUser_.id)));
            }
            if (criteria.getCustomerId() != null) {
                specification = specification.and(buildSpecification(criteria.getCustomerId(),
                    root -> root.join(TBActivityType_.customer, JoinType.LEFT).get(TBCustomer_.id)));
            }
            if (criteria.getIsGuidelineUsing() != null) {
                specification = specification.and(buildSpecification(criteria.getIsGuidelineUsing(), TBActivityType_.isGuidelineUsing));
            }

//            if (currentUser.getCustomerId() != null) {
//                List<Long> activityTypeIds = tBCustomerHasCropTypeQueryService.getActivityTypeIdsByCustomerId(currentUser.getCustomerId());
//                if (activityTypeIds.size() > 0) {
//                    LongFilter activityTypeIdFilter = new LongFilter();
//                    activityTypeIdFilter.setIn(activityTypeIds);
//                    specification = specification.and(buildSpecification(activityTypeIdFilter, TBActivityType_.id));
//                } else {
//                    specification = specification.and((root, query, cb) -> cb.disjunction());
//                }
//            }
        }
        return specification;
    }

    public TBActivityTypeDTO findActivityTypeByName(String name, Pageable pageable) {
        TBActivityTypeCriteria criteria = new TBActivityTypeCriteria();
        StringFilter nameFilter = new StringFilter();
        nameFilter.setEquals(name);
        criteria.setName(nameFilter);
        Page<TBActivityTypeDTO> page = this.findByCriteria(criteria, pageable);
        return page.getContent().size() == 0 ? null : page.getContent().get(0);
    }

    public TBActivityTypeDTO findActivityTypeByName(String name) {
        List<TBActivityType>tbActivityTypes = tBActivityTypeRepository.findAll().stream()
            .filter(x -> x.getName().equals(name))
            .collect(Collectors.toList());
        List<TBActivityTypeDTO>tbActivityTypesDTO = tBActivityTypeMapper.toDto(tbActivityTypes);
        return tbActivityTypesDTO.size() == 0 ? null : tbActivityTypesDTO.get(0);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public TBActivityTypeDTO saveUploadedFiles(TBActivityTypeDTO tbActivityTypeDTO, MultipartFile[] images) {
        if (null != images && images.length > 0) {
            String imagesPath = this.fileStorageService.storeFiles("url_logo", images);
            tbActivityTypeDTO.setUrlLogo(imagesPath);
        }
        return tbActivityTypeDTO;
    }

    public TBActivityTypeDTO updateUploadedFiles(TBActivityTypeDTO tBActivityTypeDTO,
                                             MultipartFile[] images,
                                             String deletedImage) {
        if (deletedImage != null && deletedImage != Constants.EMPTY) {
            this.fileStorageService.removeFile("url_logo", deletedImage);
        }
        tBActivityTypeDTO.setUrlLogo(null);
        tBActivityTypeDTO = this.saveUploadedFiles(tBActivityTypeDTO, images);
        return tBActivityTypeDTO;
    }

    private ArrayList<String> convertStringToList(String imagesString) {
        ArrayList<String> lstImages = new ArrayList<>();
        if (!StringUtils.isEmpty(imagesString)) {
            lstImages.addAll(Arrays.asList(imagesString.split(";")));
        }
        return lstImages;
    }

    private String convertListToString(ArrayList<String> lstOriginalImages) {
        final String[] url = {""};
        lstOriginalImages.forEach(item -> {
            if (url[0].equals("")) {
                url[0] = item;
            } else {
                url[0] = url[0] + ";" + item;
            }
        });

        return url[0];
    }

    public Page<TBActivityTypeDTO> searchTBActivityType(String query, Pageable pageable) {
        String sqlString = "select at.*\n" +
            " from tb_activity_type as at\n" +
            " where at.deleted_date IS NULL ";

        if(query != null && !query.isEmpty()) {
            sqlString = sqlString + " and ( at.description like '%" + query + "%')\n";
        }

        Query tbActivityTypeQuery = em.createNativeQuery(sqlString, TBActivityType.class);
        List<TBActivityTypeDTO> tbActivityTypeDTOs = tBActivityTypeMapper.toDto(tbActivityTypeQuery.getResultList());
        int start = Math.toIntExact(pageable.getOffset());
        int end = Math.toIntExact((start + pageable.getPageSize()) > tbActivityTypeDTOs.size() ? tbActivityTypeDTOs.size() : (start + pageable.getPageSize()));
        if(tbActivityTypeDTOs.size() > start) {
            return new PageImpl<>(tbActivityTypeDTOs.subList(start, end), pageable, tbActivityTypeDTOs.size());
        }
        return new PageImpl<>(Lists.newArrayList(), pageable, tbActivityTypeDTOs.size());
    }
}
