package com.ecep.contract.service;

import com.ecep.contract.CompanyFileType;
import com.ecep.contract.converter.CompanyFileTypeStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CompanyFileTypeLocalViewModel;
import com.ecep.contract.vo.CompanyFileTypeLocalVo;
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 = "company-file-type")
public class CompanyFileTypeService extends QueryService<CompanyFileTypeLocalVo, CompanyFileTypeLocalViewModel> {
    private final StringConverter<CompanyFileTypeLocalVo> stringConverter = new CompanyFileTypeStringConverter(this);

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

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

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

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

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

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

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