package com.ecep.contract.ds.project.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.project.repository.ProjectTypeRepository;
import com.ecep.contract.model.ProjectType;

@Lazy
@Service
@CacheConfig(cacheNames = "project-type")
public class ProjectTypeService implements IEntityService<ProjectType> {
    @Lazy
    @Autowired
    private ProjectTypeRepository projectTypeRepository;

    @Cacheable(key = "#p0")
    public ProjectType findById(Integer id) {
        return projectTypeRepository.findById(id).orElse(null);
    }

    @Cacheable(key = "'name-'+#p0")
    public ProjectType findByName(String name) {
        return projectTypeRepository.findByName(name).orElse(null);
    }

    @Cacheable(key = "'code-'+#p0")
    public ProjectType findByCode(String code) {
        return projectTypeRepository.findByCode(code).orElse(null);
    }

    @Cacheable(key = "'all'")
    public List<ProjectType> findAll() {
        return projectTypeRepository.findAll();
    }

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

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

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'all'"),
            @CacheEvict(key = "'code-'+#p0.code"),
            @CacheEvict(key = "'name-'+#p0.name"),
    })
    public ProjectType save(ProjectType type) {
        return projectTypeRepository.save(type);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'all'"),
            @CacheEvict(key = "'code-'+#p0.code"),
            @CacheEvict(key = "'name-'+#p0.name"),
    })
    public void delete(ProjectType type) {
        projectTypeRepository.delete(type);
    }

}
