package com.ecep.contract.ds.contract.service;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.contract.repository.PurchaseOrderItemRepository;
import com.ecep.contract.model.PurchaseOrderItem;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-purchase-order-item")
public class PurchaseOrderItemService implements IEntityService<PurchaseOrderItem>, QueryService<PurchaseOrderItem> {
    private static final Logger logger = LoggerFactory.getLogger(PurchaseOrderItemService.class);
    @Lazy
    @Autowired
    private PurchaseOrderItemRepository repository;

    @Cacheable(key = "#p0")
    @Override
    public PurchaseOrderItem findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Cacheable(key = "'refId-'+#p0")
    public PurchaseOrderItem findByRefId(Integer itemRefId) {
        List<PurchaseOrderItem> list = repository.findAllByRefId(itemRefId);
        if (list.isEmpty()) {
            return null;
        }
        while (list.size() > 1) {
            PurchaseOrderItem item = list.removeLast();
            repository.delete(item);
            if (logger.isInfoEnabled()) {
                logger.info("Duplicate PurchaseOrderItem, Delete {}", item);
            }
        }
        return list.getFirst();
    }

    @Override
    public Specification<PurchaseOrderItem> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(builder.like(root.get("description"), "%" + searchText + "%"));
        };
    }

    @Override
    public Page<PurchaseOrderItem> findAll(Specification<PurchaseOrderItem> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }

    @Override
    public Page<PurchaseOrderItem> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<PurchaseOrderItem> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "order", "inventory");
        return findAll(spec, pageable);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'refId-'+#p0.refId")
    })
    @Override
    public void delete(PurchaseOrderItem entity) {
        repository.delete(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"), @CacheEvict(key = "'refId-'+#p0.refId")
    })
    @Override
    public PurchaseOrderItem save(PurchaseOrderItem entity) {
        return repository.save(entity);
    }

    public List<PurchaseOrderItem> findAll(Specification<PurchaseOrderItem> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }
}
