package top.r3944realms.docchecktoolrefactored.ui.task;

import javafx.concurrent.Task;
import lombok.extern.slf4j.Slf4j;
import top.r3944realms.docchecktoolrefactored.core.AddressFileComparator;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

@Slf4j
public class AddressFileComparisonTask extends Task<AddressFileComparator.ComparisonResult> {

    private final String physicalFilePath;
    private final String logicalFilePath;
    private final AddressFileComparator.CompareMode compareMode;
    private final AddressFileComparator comparator;
    private final long timeoutSeconds; // 超时秒数

    public AddressFileComparisonTask(String physicalFilePath,
                                     String logicalFilePath,
                                     AddressFileComparator.CompareMode compareMode,
                                     long timeoutSeconds) {
        this.physicalFilePath = physicalFilePath;
        this.logicalFilePath = logicalFilePath;
        this.compareMode = compareMode;
        this.timeoutSeconds = timeoutSeconds;
        this.comparator = new AddressFileComparator();
    }

    @Override
    protected AddressFileComparator.ComparisonResult call() throws Exception {
        updateMessage("初始化文件比较...");
        comparator.setProgressCallback(new AddressFileComparator.ProgressCallback() {
            @Override
            public void onPhaseStarted(AddressFileComparator.Phase phase) {
                // 阶段开始提示
                switch (phase) {
                    case READ_PHYSICAL_CSV -> updateMessage("正在读取物理地址 CSV 文件...");
                    case READ_LOGICAL_CSV -> updateMessage("正在读取逻辑地址 CSV 文件...");
                    case COMPARE_FORWARD -> updateMessage("正在执行正向比较（物理 → 逻辑）...");
                    case COMPARE_BACKWARD -> updateMessage("正在执行反向比较（逻辑 → 物理）...");
                }
            }

            @Override
            public void onPhaseProgress(AddressFileComparator.Phase phase, int current, int total) {
                if (total <= 0) return;

                updateProgress(current, total);

                // 阶段进度提示
                switch (phase) {
                    case READ_PHYSICAL_CSV -> updateMessage(String.format("读取物理地址 CSV: %d/%d", current, total));
                    case READ_LOGICAL_CSV -> updateMessage(String.format("读取逻辑地址 CSV: %d/%d", current, total));
                    case COMPARE_FORWARD -> updateMessage(String.format("正向比较: %d/%d", current, total));
                    case COMPARE_BACKWARD -> updateMessage(String.format("反向比较: %d/%d", current, total));
                }
            }

            @Override
            public void onPhaseCompleted(AddressFileComparator.Phase phase) {
                // 阶段完成提示
                switch (phase) {
                    case READ_PHYSICAL_CSV -> updateMessage("物理地址 CSV 文件读取完成");
                    case READ_LOGICAL_CSV -> updateMessage("逻辑地址 CSV 文件读取完成");
                    case COMPARE_FORWARD -> updateMessage("正向比较完成");
                    case COMPARE_BACKWARD -> updateMessage("反向比较完成");
                }
            }
        });

        try {
            // 构建显示文本
            return comparator.compareFiles(physicalFilePath, logicalFilePath, compareMode)
                    .get(timeoutSeconds, TimeUnit.SECONDS);

        } catch (TimeoutException e) {
            updateMessage("文件比对超时，请考虑在‘文件’-‘设置’里增加‘步骤任务超时时间’。");
            log.error("文件比对超时", e);
            throw e;
        } finally {
            comparator.shutdown();
        }
    }


    @Override
    protected void cancelled() {
        super.cancelled();
        comparator.shutdown();
        updateMessage("文件比较任务已取消");
    }

}
