package SapforTestingSystem.PackageModeSupervisor;
import Common.Constants;
import Common.Global;
import Common.Utils.Utils;
import ProjectData.Files.DBProjectFile;
import ProjectData.Files.FileType;
import SapforTestingSystem.Json.*;
import SapforTestingSystem.PerformSapforTask;
import SapforTestingSystem.SapforTask.SapforTask;
import SapforTestingSystem.ThreadsPlanner.ThreadsPlanner;
import Visual_DVM_2021.Passes.PassCode_2021;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.util.Date;
import java.util.Vector;
public class PackageModeSupervisor extends ThreadsPlanner {
    SapforTasksPackage_json package_json = null;
    SapforTasksResults_json results_json = new SapforTasksResults_json();
    public PackageModeSupervisor() throws Exception {
        super(2000);
        package_json = (SapforTasksPackage_json) Utils.jsonFromFile(new File(Global.Home, Constants.package_json), SapforTasksPackage_json.class);
        Date startDate = new Date();
        results_json.StartDate = startDate.getTime();
        File started = new File(Constants.STARTED);
        FileUtils.writeStringToFile(started, String.valueOf(startDate));
        //формирование списка задач.
        File sapfor_drv = new File(Global.Home, package_json.sapfor_drv);
        setMaxKernels(package_json.kernels);
        for (SapforConfiguration_json sapforConfiguration_json : package_json.configurations) {
            for (SapforTest_json test : package_json.tests) {
                //--- чтобы было можно на нее сослаться после выполнения всех нитей.
                SapforTask task = new SapforTask();
                task.group_description = test.group_description;
                task.test_description = test.test_description;
                task.flags = sapforConfiguration_json.flags;
                task.sapfor_configuration_id = sapforConfiguration_json.id;
                results_json.tasks.add(task);
                Vector<String> codes_s = new Vector<>();
                for (PassCode_2021 code: sapforConfiguration_json.codes){
                    codes_s.add(code.toString());
                }
                task.codes = String.join(" ", codes_s);
                //---
                addThread(() -> {
                    while (!task.state.isComplete()) {
                        task.Reset();
                        new PerformSapforTask().Do(
                                sapfor_drv,
                                sapforConfiguration_json,
                                task
                        );
                    }
                });
            }
        }
        interruptThread.start();
    }
    @Override
    protected void finalize() {
        results_json.EndDate = new Date().getTime();
        //записать результаты всех задач.
        try {
            //очистка служебных файлов.
            Utils.deleteFilesByExtensions(new File(Global.Home), "proj", "dep"); //Потом txt тоже добавить.
            //--
            for (SapforTask task : results_json.tasks) {
                //--
                task.filesList = new Vector<>();
                //--
                if (task.versions.size() > 1) {
                    SapforVersion_json correctness = task.versions.get(1); //0 - исходная, 1 коррекция стиля кода.
                    File home = new File(correctness.version);
                    //задача, получить список файлов. нет вложенных папок.
                    File[] files_ = home.listFiles();
                    if (files_ != null) {
                        for (File file : files_) {
                            if (file.isFile()) {
                                DBProjectFile pf = new DBProjectFile(); //только для определения типа файла.
                                pf.file = file;
                                pf.AutoDetectProperties();
                                if (pf.fileType != FileType.forbidden)
                                    task.filesList.add(pf.file.getName());
                            }
                        }
                        //--
                        /*
                        if (task.files.size() > 0) {
                            task.filesNames = String.join("\n", task.files);
                        }
                         */
                    }
                }
            }
            Utils.jsonToFile(results_json, new File(Global.Home, Constants.results_json));
            FileUtils.writeStringToFile(new File(Constants.DONE), "");
        } catch (Exception e) {
            Global.Log.PrintException(e);
        }
        System.exit(0);
    }
}
