package net.tccn.qtask;

import dev.zhub.mk.qtask.QTask;
import net.tccn.base.Kv;
import net.tccn.base.MetaKit;

import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * Created by liangxianyou at 2019/4/20 19:59.
 */
public class TaskKit {
    private static List<QTask> qTasks;

    public static void init(List<QTask> tasks) {
        qTasks = tasks;
    }

    public static Task buildTask(String name, String plattoken, Kv para) {
        QTask taskEntity = getTaskEntity(name, plattoken);
        return buildTask(taskEntity, para);
    }

    public static Task buildTask(dev.zhub.mk.qtask.QTask qTask, Kv para) {
        Task task = qTask.createTask(para);
        task.setDbAccount(MetaKit.getDbPlat(qTask.getDbid()));
        return task;
    }

    public static QTask getTaskEntity(String name, String platid) {
        Objects.requireNonNull(name);
        Objects.requireNonNull(platid);

        Optional<QTask> any = qTasks.stream()
                .filter(x -> name.equals(x.getName()) && MetaKit.getPlatId(platid).equals(x.getPlatid()))
                .findAny();
        return any.get();
    }

    public static Object taskRun(String name, String plattoken, Kv para) {
        Task task = buildTask(name, plattoken, para);
        return QRuner.query(task);
    }

    public static Object taskRun(QTask qTask) {
        Task task = buildTask(qTask, Kv.of());
        return QRuner.query(task);
    }
}
