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

import java.util.List;

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 com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.contract.repository.PurchaseBillVoucherItemRepository;
import com.ecep.contract.model.PurchaseBillVoucherItem;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "purchase-bill-voucher-item")
public class PurchaseBillVoucherItemService
        implements IEntityService<PurchaseBillVoucherItem>, QueryService<PurchaseBillVoucherItem> {
    @Lazy
    @Autowired
    private PurchaseBillVoucherItemRepository repository;

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

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

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

    @Override
    public Page<PurchaseBillVoucherItem> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<PurchaseBillVoucherItem> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        return findAll(spec, pageable);
    }

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

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

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