package com.ecep.contract.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.ecep.contract.util.ParamUtils;
import com.ecep.contract.vm.ExtendVendorInfoViewModel;
import com.ecep.contract.vo.ContractVo;
import com.ecep.contract.vo.ExtendVendorInfoVo;

@Service
public class ExtendVendorInfoService extends QueryService<ExtendVendorInfoVo, ExtendVendorInfoViewModel> {
    @Autowired
    private VendorGroupService vendorGroupService;

    public ExtendVendorInfoVo findByContract(ContractVo contract) {
        Page<ExtendVendorInfoVo> page = findAll(ParamUtils.builder()
                .equals("contract", contract).build(),
                Pageable.ofSize(1));
        if (page.isEmpty()) {
            return null;
        }
        return page.getContent().getFirst();
    }

    public ExtendVendorInfoVo newInstanceByContract(ContractVo contract) {
        ExtendVendorInfoVo info = new ExtendVendorInfoVo();
        info.setContractId(contract.getId());

        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.setGroupId(vendorGroupService.findByCode(matcher.group(1)).getId());
                info.setCodeSequenceNumber(Integer.parseInt(matcher.group(2)));
            }
        }
        info.setAssignedProvider(false);
        info.setPrePurchase(false);
        return info;
    }

}
