package com.ecep.contract.service;

import com.ecep.contract.converter.BankStringConverter;
import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.BankViewModel;
import com.ecep.contract.vo.BankVo;
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.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

@Service
@CacheConfig(cacheNames = "bank")
public class BankService extends QueryService<BankVo, BankViewModel> {

    private final BankStringConverter stringConverter = new BankStringConverter(this);

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

    public BankVo findByName(String name) {
        Page<BankVo> page = findAll(ParamUtils.equal(name, name), Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

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

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

    @Override
    public BankStringConverter getStringConverter() {
        return stringConverter;
    }

}
