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

import java.time.LocalDateTime;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import com.ecep.contract.IEntityService;
import com.ecep.contract.ds.project.repository.ProjectBidRepository;
import com.ecep.contract.model.Project;
import com.ecep.contract.model.ProjectBid;

@Lazy
@Service
public class ProjectBidService implements IEntityService<ProjectBid> {
    private static final Logger logger = LoggerFactory.getLogger(ProjectBidService.class);

    @Lazy
    @Autowired
    private ProjectBidRepository repository;

    public ProjectBid findById(Integer id) {
        return repository.findById(id).orElse(null);
    }

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

    public List<ProjectBid> findAllByProject(Project project) {
        return repository.findAllByProject(project);
    }

    public ProjectBid save(ProjectBid bid) {
        return repository.save(bid);
    }

    @Override
    public Specification<ProjectBid> getSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("noStandardPayWayText"), "%" + searchText + "%"),
                    builder.like(root.get("noStandardContractText"), "%" + searchText + "%"),
                    builder.like(root.get("description"), "%" + searchText + "%"));

        };
    }

    public void delete(ProjectBid bid) {
        repository.delete(bid);
    }

    public ProjectBid newInstanceByProject(Project project) {
        ProjectBid approval = new ProjectBid();
        approval.setProject(project);
        approval.setApplyTime(LocalDateTime.now());
        return approval;
    }

    public List<ProjectBid> findAll(Specification<ProjectBid> spec, Sort sort) {
        return repository.findAll(spec, sort);
    }
}
