package com.yuchen.saas.park.service.service.domain.task;

import com.yuchen.saas.park.api.commons.domain.DoorAccessControlConfigTarget;
import com.yuchen.saas.park.api.commons.entity.SimpleEntity;
import com.yuchen.saas.park.api.entity.door.config.DoorAccessControlConfigIssueTask;
import com.yuchen.saas.park.api.entity.door.config.DoorAccessControlConfigIssueTaskDetails;
import lombok.Data;
import lombok.val;

import javax.validation.constraints.NotEmpty;
import java.util.List;

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

@Data(staticConstructor = "of")
public class TaskListContext {
    @NotEmpty
    private final List<DoorAccessControlConfigIssueTask> tasks;
    /**
     * 实际上应为{@link NotEmpty}
     */
    private final List<DoorAccessControlConfigIssueTaskDetails> details;
    private final DoorAccessControlConfigTarget target;

    public static TaskListContext from(@NotEmpty List<DoorAccessControlConfigIssueTask> tasks, List<DoorAccessControlConfigIssueTaskDetails> list) {
        val ids = tasks.stream().map(SimpleEntity::getId).collect(toSet());
        return of(tasks, list.stream().filter(o -> ids.contains(o.getDoorAccessControlConfigIssueTaskId())).collect(toList()), extractTarget(tasks));
    }

    private static DoorAccessControlConfigTarget extractTarget(List<DoorAccessControlConfigIssueTask> list) {
        val targets = list.stream().map(DoorAccessControlConfigIssueTask::getTarget).collect(toSet());

        if (targets.size() != 1) {
            throw new IllegalArgumentException();
        }

        return targets.stream().findFirst().orElseThrow();
    }
}