package com.ecep.contract.service;

import com.ecep.contract.VendorFileType;
import com.ecep.contract.converter.VendorFileTypeStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.VendorFileTypeLocalViewModel;
import com.ecep.contract.vo.VendorFileTypeLocalVo;
import javafx.util.StringConverter;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@CacheConfig(cacheNames = "vendor-file-type")
public class VendorFileTypeService extends QueryService<VendorFileTypeLocalVo, VendorFileTypeLocalViewModel> {
    private final StringConverter<VendorFileTypeLocalVo> stringConverter = new VendorFileTypeStringConverter(this);
    @Cacheable(key = "#p0")
    @Override
    public VendorFileTypeLocalVo findById(Integer id) {
        return super.findById(id);
    }

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

    @Caching(put = {@CachePut(key = "#p0.id"), @CachePut(key = "'all'")})
    @Override
    public VendorFileTypeLocalVo save(VendorFileTypeLocalVo entity) {
        return super.save(entity);
    }

    @Caching(put = {@CachePut(key = "#p0.id"), @CachePut(key = "'all'")})
    @Override
    public void delete(VendorFileTypeLocalVo entity) {
        super.delete(entity);
    }

    @Cacheable
    public Map<VendorFileType, VendorFileTypeLocalVo> findAll(Locale locale) {
        return findAll(ParamUtils.builder().equals("lang", locale.toLanguageTag()).build(), Pageable.unpaged()).stream()
                .collect(Collectors.toMap(VendorFileTypeLocalVo::getType, Function.identity()));
    }

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

    public VendorFileTypeLocalVo findByLocaleAndValue(Locale locale, String string) {
        return findAll(ParamUtils.builder().equals("lang", locale.toLanguageTag()).equals("value", string).build(), Pageable.ofSize(1))
                .stream().findFirst().orElse(null);
    }
}
