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

import java.util.List;

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.PermissionRepository;
import com.ecep.contract.model.Permission;

@Lazy
@Service
@CacheConfig(cacheNames = "permission")
public class PermissionService implements IEntityService<Permission> {

    @Lazy
    @Autowired
    private PermissionRepository permissionRepository;

    /*
     */
    @Cacheable(key = "'permission-'+#p0")
    public Permission findById(Integer id) {
        return permissionRepository.findById(id).orElse(null);
    }

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

    @Cacheable(key = "'permission-code-'+#p0")
    public Permission findByCode(String code) {
        // return permissionRepository.findByCode(code).orElse(null);
        throw new UnsupportedOperationException();
    }

    @Caching(evict = {
            @CacheEvict(key = "'permission-'+#p0.id"),
            // @CacheEvict(key = "'permission-code-'+#p0.code")
    })
    public Permission save(Permission role) {
        return permissionRepository.save(role);
    }

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

    @Override
    public void delete(Permission entity) {
        permissionRepository.delete(entity);
    }

    public List<Permission> findByFunctionId(int functionId) {
        return permissionRepository.findAllByFunctionId(functionId);
    }

}
