package Visual_DVM_2021.Passes.All;
import Common.Current;
import Common.Global;
import Common.UI.UI;
import Common.Utils.Utils;
import ProjectData.Files.DBProjectFile;
import ProjectData.Project.db_project_info;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import TestingSystem.Group.Group;
import TestingSystem.Test.ProjectFiles_json;
import TestingSystem.Test.Test;
import TestingSystem.TestingServer;
import Visual_DVM_2021.Passes.PassCode_2021;
import Visual_DVM_2021.Passes.PassException;
import Visual_DVM_2021.Passes.TestingSystemPass;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Vector;
public class ConvertCorrectnessTests extends TestingSystemPass<File> {
    @Override
    public String getIconPath() {
        return "/icons/DownloadAll.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        if (!Current.getAccount().isAdmin())
            Log.Writeln_("Вы не являетесь администратором");
        else return UI.Warning("Загрузить полный пакет DVM тестов на корректность и производительность.");
        return false;
    }
    @Override
    protected boolean needsAnimation() {
        return true;
    }
    @Override
    protected void performPreparation() throws Exception {
        passes.get(PassCode_2021.CloseCurrentProject);
        Current.set(Current.Root, null);
        Current.set(Current.Version, null);
        if (TestingServer.checkTasks)
            TestingServer.TimerOff();
    }
    @Override
    protected void showPreparation() throws Exception {
        UI.getMainWindow().getTestingWindow().ShowAutoActualizeTestsState();
    }
    @Override
    protected void ServerAction() throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.RefreshDVMTests));
        Vector<Group> groups = (Vector<Group>) response.object;
        System.out.println("найдено " + groups.size() + " групп");
        Test test = null;
        Vector<Test> tests = null;
        for (Group group : groups) {
            ShowMessage1("Создание группы " + group.description);
            tests = new Vector<>();
            group.genName();
            group.sender_name = Current.getAccount().name;
            group.sender_address = Current.getAccount().email;
            //->>
            //->>
            for (String testFileName : group.testsFiles.keySet()) {
                ShowMessage2("Создание теста " + testFileName);
                test = new Test();
                test.genName();
                test.description = Utils.getNameWithoutExtension(testFileName) + "_" + group.language.getDVMCompile();
                test.date = new Date().getTime();
                test.sender_name = Current.getAccount().name;
                test.sender_address = Current.getAccount().email;
                test.group_id = group.id;
                //->>
                File testProject = Paths.get(Global.TempDirectory.getAbsolutePath(), test.id).toFile();
                Utils.forceDeleteWithCheck(testProject);
                FileUtils.forceMkdir(testProject);
                File testFile = Paths.get(testProject.getAbsolutePath(), testFileName).toFile();
                Utils.unpackFile(group.testsFiles.get(testFileName), testFile);
                //----
                ProjectFiles_json projectFiles_json = new ProjectFiles_json();
                //----
                DBProjectFile testDBProjectFile = new DBProjectFile();
                testDBProjectFile.name = testFile.getName();
                testDBProjectFile.file = testFile;
                testDBProjectFile.AutoDetectProperties();
                //---
                projectFiles_json.files.add(testDBProjectFile);
                //---
                test.files_json = Utils.jsonToPrettyFormat(Utils.gson.toJson(projectFiles_json));
                //->
                //без создания бд!!
                db_project_info vizTestProject = new db_project_info(testProject, "", false);
                switch (group.language) {
                    case fortran:
                        test.dim = Current.getSapfor().getTextMaxDim(testFile, vizTestProject);
                        break;
                    case c:
                        test.dim = Utils.getCTestMaxDim(testFile);
                        break;
                }
                //-
                //архивация.
                File archive = Utils.getTempFileName("test_archive");
                if (passes.get(PassCode_2021.ZipFolderPass).Do(vizTestProject.Home.getAbsolutePath(), archive.getAbsolutePath())) {
                    test.project_archive_bytes = Utils.packFile(archive);
                    if (test.dim >= 0)
                        tests.add(test);
                    else UI.Info("для теста " + testFileName + " не удалось определить размерность");
                } else throw new PassException("Не удалось заархивировать тест");
            }
            //->>
            if (!tests.isEmpty()) {
                ShowMessage1("Публикация группы " + group.description);
                Command(new ServerExchangeUnit_2021(ServerCode.PublishObject, "", group));
                for (Test test1 : tests) {
                    ShowMessage2("Публикация теста " + test1.description);
                    Command(new ServerExchangeUnit_2021(ServerCode.PublishObject, "", test1));
                }
            }
        }
    }
    @Override
    protected void performFinish() throws Exception {
        super.performFinish();
        passes.get(PassCode_2021.SynchronizeTests).Do();
    }
}
