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

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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.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.contract.repository.ExtendVendorInfoRepository;
import com.ecep.contract.ds.vendor.service.VendorGroupService;
import com.ecep.contract.model.Contract;
import com.ecep.contract.model.ExtendVendorInfo;
import com.ecep.contract.util.SpecificationUtils;
import com.fasterxml.jackson.databind.JsonNode;

@Lazy
@Service
@CacheConfig(cacheNames = "contract-ext-ven-info")
public class ExtendVendorInfoService implements IEntityService<ExtendVendorInfo>, QueryService<ExtendVendorInfo> {
    @Lazy
    @Autowired
    private ExtendVendorInfoRepository repository;
    @Lazy
    @Autowired
    private VendorGroupService vendorGroupService;

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

    @Cacheable(key = "'bycontract-'+#p0.id")
    public ExtendVendorInfo findByContract(Contract contract) {
        return repository.findByContractId(contract.getId()).orElse(null);
    }

    @Caching(evict = {
            @CacheEvict(key = "#p0.id"),
            @CacheEvict(key = "'bycontract-'+#p0.contract.id")
    })
    public ExtendVendorInfo save(ExtendVendorInfo bidVendor) {
        return repository.save(bidVendor);
    }

    @Caching(
            evict = {
                    @CacheEvict(key = "#p0.id"),
                    @CacheEvict(key = "'bycontract-'+#p0.contract.id")
            }
    )
    @Override
    public void delete(ExtendVendorInfo bidVendor) {
        repository.delete(bidVendor);
    }
    
    @Override
    public Page<ExtendVendorInfo> findAll(Specification<ExtendVendorInfo> spec, Pageable pageable) {
        return repository.findAll(spec, pageable);
    }
    
    @Override
    public Specification<ExtendVendorInfo> getSpecification(String searchText) {
        if (!StringUtils.hasText(searchText)) {
            return null;
        }
        return (root, query, builder) -> {
            return builder.or(
                    builder.like(root.get("contract").get("code"), "%" + searchText + "%"),
                    builder.like(root.get("contract").get("name"), "%" + searchText + "%"),
                    builder.like(root.get("codeSequenceNumber").as(String.class), "%" + searchText + "%")
            );
        };
    }
    
    @Override
    public Page<ExtendVendorInfo> findAll(JsonNode paramsNode, Pageable pageable) {
        Specification<ExtendVendorInfo> spec = null;
        if (paramsNode.has("searchText")) {
            spec = getSpecification(paramsNode.get("searchText").asText());
        }
        // field
        spec = SpecificationUtils.andParam(spec, paramsNode, "contract");
        return findAll(spec, pageable);
    }

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

    public void deleteById(int id) {
        repository.deleteById(id);
    }

    public ExtendVendorInfo newInstanceByContract(Contract contract) {
        ExtendVendorInfo info = new ExtendVendorInfo();
        info.setContract(contract);

        if (StringUtils.hasText(contract.getCode())) {
            String regex = "-([A-Z]{1,4})(\\d{1,4})";
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(contract.getCode());
            if (matcher.find()) {
                info.setGroup(vendorGroupService.findByCode(matcher.group(1)));
                info.setCodeSequenceNumber(Integer.parseInt(matcher.group(2)));
            }
        }
        info.setAssignedProvider(false);
        info.setPrePurchase(false);
        return info;
    }
}
