package com.bytesw.bytebot.service;

import com.bytesw.bytebot.service.BusinessParameterService;
import com.bytesw.bytebot.repository.BusinessParameterRepository;
import com.bytesw.bytebot.repository.BusinessParameterConfigurationRepository;
import com.bytesw.bytebot.model.BusinessParameter;
import com.bytesw.bytebot.model.BusinessParameterConfiguration;
import com.bytesw.bytebot.bean.BusinessParameterConfigurationBean;
import com.bytesw.xdf.exception.NotFoundException;
import com.bytesw.xdf.service.XDFService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigInteger;
import java.util.Optional;

@Service
@Transactional
public class BusinessParameterConfigurationService extends XDFService<BusinessParameterConfiguration, BusinessParameterConfigurationBean, BigInteger> {
    @Autowired
    private BusinessParameterService gatewayBusinessParameterService;
    @Autowired
    private BusinessParameterRepository businessParameterRepository;
    @Autowired
    private BusinessParameterConfigurationRepository businessParameterConfigurationRepository;

    protected BusinessParameterConfigurationService(BusinessParameterConfigurationRepository repository) {
        super(repository);
    }

    @Override
    protected BusinessParameterConfiguration toModel(BusinessParameterConfiguration model, BusinessParameterConfigurationBean bean) {
        if (model == null) {
            model = new BusinessParameterConfiguration();
        }
        BeanUtils.copyProperties(bean, model);
        if (bean.getBusinessParameters() == null) {
            throw new NotFoundException("BusinessParameter can not be null");
        }
        Optional<BusinessParameter> businessParameterOptional = businessParameterRepository.findById(bean.getBusinessParameters().getId());
        if (!businessParameterOptional.isPresent()) {
            throw new NotFoundException("BusinessParameter not found " + bean.getBusinessParameters().getId());
        }
        model.setBusinessParameter(businessParameterOptional.get());
        return model;
    }

    @Override
    protected BusinessParameterConfigurationBean toBean(BusinessParameterConfiguration model) {
        BusinessParameterConfigurationBean bean = new BusinessParameterConfigurationBean();
        BeanUtils.copyProperties(model, bean);
        bean.setBusinessParameters(gatewayBusinessParameterService.toBean(model.getBusinessParameter()));
        return bean;
    }
}
