package cn.axzo.msg.center.message.service.todo.manage.broadcast;

import cn.axzo.msg.center.dal.TodoDao;
import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.domain.persistence.BaseEntityExt;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

import static java.util.stream.Collectors.toList;

/**
 * @author yanglin
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class TodoBroadcaster {

    private final TodoMqBroadcaster todoMqBroadcaster;
    private final TodoPullBroadcaster todoPullBroadcaster;
    private final TodoDao todoDao;

    public void fireTodoUpdates(String operation, Todo todo) {
        fireTodoUpdates(operation, Collections.singletonList(todo));
    }

    public void fireTodoUpdates(String operation, List<Todo> todos) {
        if (CollectionUtils.isEmpty(todos))
            return;
        List<Long> todoIds = todos.stream()
                .map(BaseEntityExt::getId)
                .distinct()
                .collect(toList());
        List<Todo> upToDateTodos = todoDao.listByIds(todoIds);
        if (upToDateTodos.isEmpty()) {
            log.warn("发送待办通知时, 查询不到最新的待办信息. todoIds={}", JSON.toJSONString(todoIds));
            return;
        }
        todoMqBroadcaster.fireTodoUpdated(operation, todos);
        todoPullBroadcaster.fireTodoChanged(todos);
    }

}