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

import com.bcxin.tenant.open.domains.entities.RdDeviceLocationHistoryEntity;
import com.bcxin.tenant.open.domains.entities.valueTypes.GeoPointValueType;
import com.bcxin.tenant.open.domains.repositories.RdDeviceLocationHistoryRepository;
import com.bcxin.tenant.open.domains.services.DeviceLocationHistoryService;
import com.bcxin.tenant.open.domains.services.commands.BatchDeviceLocationHistoryCommand;
import com.bcxin.tenant.open.infrastructures.UnitWork;
import org.springframework.stereotype.Service;

@Service
public class DeviceLocationHistoryServiceImpl implements DeviceLocationHistoryService {

    private final UnitWork unitWork;
    private final RdDeviceLocationHistoryRepository deviceLocationHistoryRepository;

    public DeviceLocationHistoryServiceImpl(UnitWork unitWork,
                                            RdDeviceLocationHistoryRepository deviceLocationHistoryRepository) {
        this.unitWork = unitWork;
        this.deviceLocationHistoryRepository = deviceLocationHistoryRepository;
    }

    @Override
    public void batch(BatchDeviceLocationHistoryCommand command) {
        String tranId = this.unitWork.beginTransaction();
        try {
            for(BatchDeviceLocationHistoryCommand.DeviceLocationHistoryItemCommand item : command.getHistoryItems()) {
                this.deviceLocationHistoryRepository.insert(RdDeviceLocationHistoryEntity.create(
                        item.getDeviceId(),
                        item.getDispatchNo(),
                        GeoPointValueType.create( item.getLat(), item.getLon()))
                );
            }
            this.unitWork.commit(tranId);
        } catch (Exception ex) {
            this.unitWork.rollback(tranId);
        }
    }
}
