package cn.axzo.msg.center.dal;

import cn.axzo.msg.center.domain.entity.Todo;
import cn.axzo.msg.center.domain.entity.TodoBusiness;
import cn.axzo.msg.center.domain.persistence.BaseEntityExt;
import cn.axzo.msg.center.service.enums.BizCategoryEnum;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

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

/**
 * @author yanglin
 */
public class TodoBusinesses {

    private final Map<Long, TodoBusiness> id2Business;
    private final List<Todo> todos;

    TodoBusinesses(List<TodoBusiness> businesses, List<Todo> todos) {
        id2Business = businesses.stream()
                .collect(toMap(BaseEntityExt::getId, Function.identity()));
        this.todos = todos;
    }

    public List<Todo> getTodoByCategory(BizCategoryEnum category) {
        if (todos == null)
            return Collections.emptyList();
        return todos.stream()
                .filter(todo -> {
                    TodoBusiness business = findBusiness(todo).orElse(null);
                    return business != null && business.getBizCategory() == category;
                })
                .collect(toList());
    }

    public Optional<TodoBusiness> findBusiness(Todo todo) {
        if (todo == null)
            return Optional.empty();
        return findBusiness(todo.getTodoBusinessId());
    }

    public Optional<TodoBusiness> findBusiness(Long businessId) {
        return Optional.ofNullable(id2Business.get(businessId));
    }
}