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.ProjectFundPlanRepository;
import com.ecep.contract.model.Project;
import com.ecep.contract.model.ProjectFundPlan;

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

    @Lazy
    @Autowired
    private ProjectFundPlanRepository repository;

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

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

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

    public ProjectFundPlan save(ProjectFundPlan fundPlan) {
        return repository.save(fundPlan);
    }

    @Override
    public Specification<ProjectFundPlan> getSpecification(String searchText) {
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("payTerm"), "%" + searchText + "%"),
                    builder.like(builder.toString(root.get("payRatio")), "%" + searchText + "%"),
                    builder.like(builder.toString(root.get("payCurrency")), "%" + searchText + "%")
            );
        };
    }

    public void delete(ProjectFundPlan fundPlan) {
        repository.delete(fundPlan);
    }

    public ProjectFundPlan newInstanceByProject(Project project) {
        ProjectFundPlan fundPlan = new ProjectFundPlan();
        fundPlan.setProject(project);
        fundPlan.setUpdateDate(LocalDateTime.now());
        return fundPlan;
    }

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