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

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 org.springframework.util.StringUtils;

import com.ecep.contract.IEntityService;
import com.ecep.contract.QueryService;
import com.ecep.contract.ds.company.repository.CompanyBlackReasonRepository;
import com.ecep.contract.model.Company;
import com.ecep.contract.model.CompanyBlackReason;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
public class CompanyBlackReasonService implements IEntityService<CompanyBlackReason>, QueryService<CompanyBlackReason> {
    private static final Logger logger = LoggerFactory.getLogger(CompanyContactService.class);

    @Autowired
    private CompanyBlackReasonRepository repository;

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

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

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

    public void delete(CompanyBlackReason entity) {
        repository.delete(entity);
    }

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

    public List<CompanyBlackReason> findAllByCompany(Company company) {
        return repository.findAllByCompany(company);
    }

    public CompanyBlackReason save(CompanyBlackReason companyBlackReason) {
        return repository.save(companyBlackReason);
    }

    @Override
    public Page<CompanyBlackReason> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<CompanyBlackReason> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "company");
        return findAll(spec, pageable);
    }
}
