package com.ecep.contract.ds.vendor.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.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ds.vendor.repository.VendorGroupRepository;
import com.ecep.contract.model.VendorGroup;

@Lazy
@Service
@CacheConfig(cacheNames = "vendor-group")
public class VendorGroupService implements IEntityService<VendorGroup> {
    @Lazy
    @Autowired
    private VendorGroupRepository vendorGroupRepository;

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

    public VendorGroup findByName(String name) {
        return vendorGroupRepository.findByName(name).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public VendorGroup findByCode(String code) {
        return vendorGroupRepository.findByCode(code).orElse(null);
    }

    @Cacheable(key = "'all'")
    public List<VendorGroup> findAll() {
        return vendorGroupRepository.findAll();
    }

    public Page<VendorGroup> findAll(Specification<VendorGroup> spec, Pageable pageable) {
        return vendorGroupRepository.findAll(spec, pageable);
    }

    @Override
    public Specification<VendorGroup> getSpecification(String searchText) {
        return null;
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public VendorGroup save(VendorGroup group) {
        return vendorGroupRepository.save(group);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'code-'+#p0.name"),
            @CacheEvict(key = "'all'"),
    })
    public void delete(VendorGroup entity) {
        vendorGroupRepository.delete(entity);
    }

    public VendorGroup newInstance() {
        VendorGroup group = new VendorGroup();
        group.setCode("");
        group.setName("");
        group.setDescription("");
        group.setActive(true);
        group.setPriceComparison(true);
        group.setRequireQuotationSheetForBid(true);
        group.setCanPrePurchase(false);
        return group;
    }

}
