package com.base.task.core.listener;

import com.base.task.core.TaskCache;
import com.base.task.handler.TaskHandler;
import com.base.task.model.Task;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import java.io.File;
import java.util.Iterator;

@Slf4j
public class TaskResultListener extends FileAlterationListenerAdaptor {

    private Task task;

    public TaskResultListener(Task task) {
        this.task = task;
    }


    @Override
    public void onStart(FileAlterationObserver observer) {
        super.onStart(observer);
    }

    @Override
    public void onFileCreate(File file) {
        try{

            log.info(task.getTaskSerial() + " execute !");
            log.info(file.getPath() + " create success!");
            //这里sleep3秒等待写文件
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                log.error(e.getMessage(), e);
            }
            if (task != null){
                task.getProcess().destroy();
                task.getTaskHandler().taskExecute(task);
                //在当前任务中剔除
            /*    FileMonitor.getInstance().removeListener(task);*/

                TaskCache.getInstance().removeCurrentTask(task);
                //销毁监听器
                FileMonitor.getInstance().stopListenerFile(file,task);
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }
    }
}