package com.ecep.contract.ds.other.service;

import org.springframework.beans.factory.annotation.Autowired;
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.context.annotation.Lazy;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ds.other.repository.FunctionRepository;
import com.ecep.contract.model.Function;

@Lazy
@Service
@CacheConfig(cacheNames = "function")
public class FunctionService implements IEntityService<Function> {
    @Lazy
    @Autowired
    private FunctionRepository repository;

    /*
    
    
     */
    @Cacheable(key = "#p0")
    public Function findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id")
    })
    public Function save(Function role) {
        return repository.save(role);
    }

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

    public Page<Function> findAll(Specification<Function> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }

    @Override
    public Specification<Function> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("key"), "%" + searchText + "%"),
                    builder.like(root.get("name"), "%" + searchText + "%"),
                    builder.like(root.get("controller"), "%" + searchText + "%"),
                    builder.like(root.get("icon"), "%" + searchText + "%")
            );
        };
    }
}
