package com.ecep.contract.service;

import com.ecep.contract.converter.ContractGroupStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.ContractGroupViewModel;
import com.ecep.contract.vo.ContractGroupVo;
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.cache.annotation.Caching;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@CacheConfig(cacheNames = "contract-group")
public class ContractGroupService extends QueryService<ContractGroupVo, ContractGroupViewModel> {

    private final ContractGroupStringConverter converter = new ContractGroupStringConverter(this);

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

    public ContractGroupVo findByCode(String code) {
        return findAll(ParamUtils.builder().equals("code", code).build(), Pageable.ofSize(1)).stream().findFirst().orElse(null);
    }

    public ContractGroupVo findByName(String name) {
        return findAll(ParamUtils.builder().equals("name", name).build(), Pageable.ofSize(1)).stream().findFirst().orElse(null);
    }


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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"), @CacheEvict(key = "'groups'")
    })
    @Override
    public ContractGroupVo save(ContractGroupVo entity) {
        return super.save(entity);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"), @CacheEvict(key = "'groups'")
    })
    @Override
    public void delete(ContractGroupVo entity) {
        super.delete(entity);
    }

    @Override
    public StringConverter<ContractGroupVo> getStringConverter() {
        return converter;
    }
}