package com.ecep.contract.service;

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

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 com.ecep.contract.ContractFileType;
import com.ecep.contract.converter.ContractFileTypeStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.ContractFileTypeLocalViewModel;
import com.ecep.contract.vo.ContractFileTypeLocalVo;

import javafx.util.StringConverter;

@Service
@CacheConfig(cacheNames = "contract-file-type")
public class ContractFileTypeService extends QueryService<ContractFileTypeLocalVo, ContractFileTypeLocalViewModel> {
    private final StringConverter<ContractFileTypeLocalVo> stringConverter = new ContractFileTypeStringConverter(this);

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

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

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

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

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

    @Cacheable
    public ContractFileTypeLocalVo findByType(Locale locale, ContractFileType type) {
        return findAll(ParamUtils.builder().equals("lang", locale.toLanguageTag()).equals("type", type).build(), Pageable.ofSize(1)).stream().findFirst().orElse(null);
    }

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

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