package com.bcxin.tenant.open.domains.services.impls;

import com.bcxin.tenant.open.domains.entities.DeviceCommunicatedLogDetailEntity;
import com.bcxin.tenant.open.domains.repositories.DeviceCommunicatedLogDetailRepository;
import com.bcxin.tenant.open.domains.services.DeviceCommunicatedLogDetailService;
import com.bcxin.tenant.open.domains.services.commands.CreateSyncDeviceCommunicatedLogDetailCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import com.bcxin.tenant.open.infrastructures.components.JsonProvider;
import com.bcxin.tenant.open.infrastructures.exceptions.BadTenantException;
import org.springframework.stereotype.Service;

@Service
public class DeviceCommunicatedLogDetailServiceImpl implements DeviceCommunicatedLogDetailService {

    private final UnitWork unitWork;
    private final JsonProvider jsonProvider;
    private final DeviceCommunicatedLogDetailRepository deviceCommunicatedLogDetailRepository;

    public DeviceCommunicatedLogDetailServiceImpl(UnitWork unitWork,
                                                  JsonProvider jsonProvider,
                                                  DeviceCommunicatedLogDetailRepository deviceCommunicatedLogDetailRepository) {
        this.unitWork = unitWork;
        this.jsonProvider = jsonProvider;
        this.deviceCommunicatedLogDetailRepository = deviceCommunicatedLogDetailRepository;
    }

    @Override
    public void dispatch(CreateSyncDeviceCommunicatedLogDetailCommand command) {
        String tranId = this.unitWork.beginTransaction();
        try {
            DeviceCommunicatedLogDetailEntity deviceCommunicatedLogDetail =
                    this.jsonProvider.toObject(DeviceCommunicatedLogDetailEntity.class, command.getContent());
            if (deviceCommunicatedLogDetail == null) {
                throw new BadTenantException(String.format("无效数据格式:%s", command.getContent()));
            }

            if (this.deviceCommunicatedLogDetailRepository.getByNoPkId(deviceCommunicatedLogDetail.getId()) != null) {
                this.deviceCommunicatedLogDetailRepository.update(deviceCommunicatedLogDetail);
            } else {
                this.deviceCommunicatedLogDetailRepository.insert(deviceCommunicatedLogDetail);
            }

            this.unitWork.commit(tranId);
        } catch (Exception ex) {
            this.unitWork.rollback(tranId);
            throw ex;
        }
    }
}
