package com.ecep.contract.service;

import com.ecep.contract.converter.ProductUsageStringConverter;
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.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.ProductUsageViewModel;
import com.ecep.contract.vo.ProductUsageVo;

@Service
@CacheConfig(cacheNames = "productUsageCache")
public class ProductUsageService extends QueryService<ProductUsageVo, ProductUsageViewModel> {
    private final StringConverter<ProductUsageVo> stringConverter = new ProductUsageStringConverter(this);

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

    public ProductUsageVo findByName(String string) {
        return findOneByProperty("name", string);
    }

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

    @Override
    @CacheEvict(allEntries = true)
    public ProductUsageVo save(ProductUsageVo usage) {
        return super.save(usage);
    }

    @Override
    @CacheEvict(allEntries = true)
    public void delete(ProductUsageVo usage) {
        super.delete(usage);
    }

    public ProductUsageVo findByCode(String code) {
        Page<ProductUsageVo> page = findAll(ParamUtils.builder().equals("code", code).build(), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }


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