package _VisualDVM.TestingSystem.SAPFOR;
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.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);
        sapfor_drv = new File(Utils_.getHomeDirectory(), Utils_.getDateName("SAPFOR_F"));
        FileUtils.copyFile(sapfor_src, sapfor_drv);
        if (!sapfor_drv.setExecutable(true))
            throw new Exception("Не удалось сделать файл " + sapfor_drv.getName() + " исполняемым!");
        File PID = new File("PID");
        FileUtils.writeStringToFile(PID, sapfor_drv.getName(), Charset.defaultCharset());
        //---
        Date startDate = new Date();
        File started = new File(Constants.STARTED);
        FileUtils.writeStringToFile(started, String.valueOf(startDate));
        //формирование списка задач.
        setMaxKernels(package_json.kernels);
        for (SapforTask task : package_json.tasks)
            addThread(new TaskThread(task, sapfor_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(Constants.DONE), "");
            //--
            //Очистка
            //очистка служебных файлов.
            Utils.deleteFilesByExtensions(Utils_.getHomeDirectory(),
                    "proj", "dep", "jar"
                    //  ,"sh", "exe", "bat"
            );
            //удаление сапфора
            if (sapfor_drv.exists())
                FileUtils.forceDelete(sapfor_drv);
        } catch (Exception e) {
            Utils_.MainLog.PrintException(e);
        }
        System.exit(0);
    }
}
