package com.ecep.contract.service;

import javafx.util.StringConverter;
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.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ecep.contract.converter.CustomerCatalogStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CustomerCatalogViewModel;
import com.ecep.contract.vo.CustomerCatalogVo;

@Service
@CacheConfig(cacheNames = "customer-catalog")
public class CustomerCatalogService extends QueryService<CustomerCatalogVo, CustomerCatalogViewModel> {

    private final CustomerCatalogStringConverter stringConverter = new CustomerCatalogStringConverter(this);

    @Override
    @Cacheable(key = "#id")
    public CustomerCatalogVo findById(Integer id) {
        return super.findById(id);
    }

    public CustomerCatalogVo findByName(String string) {
        return findAll(ParamUtils.builder().equals("name", string).build(), Pageable.ofSize(1)).stream().findFirst().orElse(null);
    }

    @Override
    @Cacheable(key = "'all'")
    public java.util.List<CustomerCatalogVo> findAll() {
        return super.findAll();
    }

    @Caching(evict = {@CacheEvict(key = "'all'"), @CacheEvict(key = "#entity.id")})
    @Override
    public CustomerCatalogVo save(CustomerCatalogVo entity) {
        return super.save(entity);
    }

    @Caching(evict = {@CacheEvict(key = "'all'"), @CacheEvict(key = "#entity.id")})
    @Override
    public void delete(CustomerCatalogVo entity) {
        super.delete(entity);
    }

    @Override
    public StringConverter<CustomerCatalogVo> getStringConverter() {
        return stringConverter;
    }
}
