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

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
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.ProjectCostItemRepository;
import com.ecep.contract.model.ProjectCost;
import com.ecep.contract.model.ProjectCostItem;

@Lazy
@Service
public class ProjectCostItemService implements IEntityService<ProjectCostItem> {
    @Lazy
    @Autowired
    private ProjectCostItemRepository repository;

    @Override
    public ProjectCostItem findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

    public List<ProjectCostItem> findByCost(ProjectCost cost) {
        return repository.findByCost(cost);
    }

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

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

    @Override
    public void delete(ProjectCostItem entity) {
        repository.delete(entity);
    }

    @Override
    public ProjectCostItem save(ProjectCostItem entity) {
        return repository.save(entity);
    }

}
