package com.ecep.contract.task;

import java.util.Random;
import java.util.concurrent.TimeUnit;

import com.ecep.contract.Desktop;
import com.ecep.contract.MessageHolder;

/**
 * 演示用的测试任务类，用于测试任务监控系统
 */
public class DemoTask extends Tasker<Object> {

    private final String taskName;
    private final int durationSeconds;
    private final boolean shouldFail;
    private final Random random = new Random();

    public DemoTask(String taskName, int durationSeconds, boolean shouldFail) {
        this.taskName = taskName;
        this.durationSeconds = durationSeconds;
        this.shouldFail = shouldFail;
        // 设置任务标题
        updateTitle("演示任务: " + taskName);
    }

    /**
     * 创建并启动一个测试任务
     */
    public static void startDemoTask(String name, int duration, boolean fail) {
        DemoTask task = new DemoTask(name, duration, fail);
        // 启动任务
        Desktop.instance.getTaskMonitorCenter().registerAndStartTask(task);
    }

    /**
     * 运行多个测试任务的演示
     */
    public static void runDemo() {
        // 创建几个不同类型的测试任务
        startDemoTask("正常完成任务", 5, false);

        // 延迟启动其他任务
        Desktop.instance.getExecutorService().submit(() -> {
            try {
                TimeUnit.SECONDS.sleep(2);
                startDemoTask("失败任务示例", 3, true);

                TimeUnit.SECONDS.sleep(2);
                startDemoTask("长时间运行任务", 10, false);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
    }

    @Override
    protected Object execute(MessageHolder holder) throws Exception {
        holder.info("开始执行任务: " + taskName);

        // 模拟任务执行过程
        for (int i = 0; i < durationSeconds; i++) {
            // 检查任务是否被取消
            if (isCancelled()) {
                holder.info("任务被取消: " + taskName);
                updateMessage("任务已取消");
                return "任务已取消";
            }

            // 更新进度
            double progress = (double) i / durationSeconds;
            updateProgress(progress, 1.0);
            updateMessage("处理中... (" + (i + 1) + " / " + durationSeconds + ")");

            // 模拟随机延迟
            Thread.sleep(1000);
        }

        // 根据配置决定任务是成功还是失败
        if (shouldFail) {
            holder.warn("任务故意失败:" + taskName);
            throw new Exception("这是一个测试用的任务失败异常");
        }

        holder.info("任务执行完成: " + taskName);
        updateProgress(1.0, 1.0);
        updateMessage("任务完成");
        return "任务执行成功: " + taskName;
    }
}