package _VisualDVM.TestingSystem.SAPFOR;
import Common.CommonConstants;
import Common.Utils.Utils_;
import _VisualDVM.Constants;
import _VisualDVM.TestingSystem.Common.TaskThread;
import _VisualDVM.TestingSystem.Common.ThreadsPlanner.ThreadsPlanner;
import _VisualDVM.TestingSystem.SAPFOR.Json.SapforPackage_json;
import _VisualDVM.TestingSystem.SAPFOR.SapforTask.SapforTask;
import _VisualDVM.Utils;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.Date;
public class PackageModeSupervisor extends ThreadsPlanner {
    SapforPackage_json package_json = null;
   // File sapfor_drv = null;
    public PackageModeSupervisor() throws Exception {
        super(2000);
        package_json = (SapforPackage_json) Utils_.jsonFromFile(new File(Constants.package_json), SapforPackage_json.class);
        //--
        File sapfor_src = new File(package_json.sapfor_drv);
        //--
        String pid_prefix = Utils_.getDateName("SAPFOR_F");
        //--
        File PID = new File("PID");
        FileUtils.writeStringToFile(PID, pid_prefix, Charset.defaultCharset());
        //---
        Date startDate = new Date();
        File started = new File(CommonConstants.STARTED);
        FileUtils.writeStringToFile(started, String.valueOf(startDate));
        //формирование списка задач.
        setMaxKernels(package_json.kernels);
        for (SapforTask task : package_json.tasks) {
            File task_drv = new File(Utils_.getHomeDirectory(),pid_prefix+"_"+task.id);
            Files.createSymbolicLink(task_drv.toPath(), sapfor_src.toPath());
            addThread(new TaskThread(task, task_drv));
        }
        interruptThread.start();
    }
    @Override
    public String printThread(Integer id) {
        TaskThread taskThread = (TaskThread) threads.get(id);
        return taskThread.task.getSummary();
    }
    @Override
    protected void finalize() {
        //записать результаты всех задач.
        try {
            Utils_.jsonToFile(package_json, new File(Constants.package_json));
            FileUtils.writeStringToFile(new File(CommonConstants.DONE), "");
            //--
            //Очистка
            //очистка служебных файлов.
            Utils.deleteFilesByExtensions(Utils_.getHomeDirectory(),
                    "proj", "dep", "jar"
                    //  ,"sh", "exe", "bat"
            );
            //удаление сапфора exception
          //  if (sapfor_drv.exists())
          //      FileUtils.forceDelete(sapfor_drv);
        } catch (Exception e) {
            Utils_.MainLog.PrintException(e);
        }
        System.exit(0);
    }
}
