package com.ecep.contract.service;

import java.util.HashMap;
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.CustomerFileType;
import com.ecep.contract.converter.CustomerFileTypeStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.CompanyCustomerFileTypeLocalViewModel;
import com.ecep.contract.vo.CustomerFileTypeLocalVo;

import javafx.util.StringConverter;

@Service
@CacheConfig(cacheNames = "company-customer-file-type")
public class CompanyCustomerFileTypeService
        extends QueryService<CustomerFileTypeLocalVo, CompanyCustomerFileTypeLocalViewModel> {
    private final StringConverter<CustomerFileTypeLocalVo> stringConverter = new CustomerFileTypeStringConverter(this);

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

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

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

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

    @Cacheable
    public Map<CustomerFileType, CustomerFileTypeLocalVo> findAll(Locale locale) {
        Map<String, Object> params = new HashMap<>();
        params.put("lang", locale.toLanguageTag());
        return findAll(params, Pageable.unpaged()).stream()
                .collect(Collectors.toMap(CustomerFileTypeLocalVo::getType, Function.identity()));
    }

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

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