package com.bcxin.tenant.open.domains.eventListeners;

import com.bcxin.tenant.open.domains.entities.DeviceCommunicatedLogDetailEntity;
import com.bcxin.tenant.open.domains.events.PreparedRoomCommunicatedGroupEvent;
import com.bcxin.tenant.open.domains.repositories.ConfigOfBillRepository;
import com.bcxin.tenant.open.domains.services.DeviceCommunicatedLogService;
import com.bcxin.tenant.open.domains.services.commands.CreateDeviceCommunicatedLogCommand;
import com.bcxin.tenant.open.domains.utils.DeviceCommunicatedLogDetailUtils;
import com.bcxin.tenant.open.infrastructures.components.IdWorker;
import com.bcxin.tenant.open.infrastructures.exceptions.BadTenantException;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.stream.Collectors;

@Component
public class PreparedRoomCommunicatedGroupListener_DeviceCommunicatedLogDetail
        implements ApplicationListener<PreparedRoomCommunicatedGroupEvent> {
    private final DeviceCommunicatedLogService deviceCommunicatedLogService;
    private final IdWorker idWorker;
    private final ConfigOfBillRepository configOfBillRepository;

    public PreparedRoomCommunicatedGroupListener_DeviceCommunicatedLogDetail(
            DeviceCommunicatedLogService deviceCommunicatedLogService, IdWorker idWorker,
            ConfigOfBillRepository configOfBillRepository) {
        this.deviceCommunicatedLogService = deviceCommunicatedLogService;
        this.idWorker = idWorker;
        this.configOfBillRepository = configOfBillRepository;
    }

    @Override
    public void onApplicationEvent(PreparedRoomCommunicatedGroupEvent event) {
        Collection<DeviceCommunicatedLogDetailEntity> logDetails =
                DeviceCommunicatedLogDetailUtils.build(
                        configOfBillRepository.get(),
                        idWorker,
                        event.getRoomCommunicatedGroups()
                );

        if (CollectionUtils.isEmpty(logDetails)) {
            String roomId =
                    event.getRoomCommunicatedGroups().stream().map(ix -> ix.getRoomId()).distinct().collect(Collectors.joining(";"));
            throw new BadTenantException(String.format("无生成有效调度记录(%s), 请联系管理员", roomId));
        }

        this.deviceCommunicatedLogService.dispatch(
                CreateDeviceCommunicatedLogCommand.create(logDetails)
        );
    }
}
