package Visual_DVM_2021.Passes.All;
import Common.Constants;
import Common.Current;
import Common.UI.UI;
import Common.Utils.Utils;
import ProjectData.Project.db_project_info;
import Repository.Server.ServerCode;
import Repository.Server.ServerExchangeUnit_2021;
import TestingSystem.Test.ProjectFiles_json;
import TestingSystem.Test.Test;
import Visual_DVM_2021.Passes.PassCode_2021;
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;
public class PublishTest extends TestingSystemPass<Test> {
    @Override
    public String getIconPath() {
        return "/icons/RedAdd.png";
    }
    @Override
    public String getButtonText() {
        return "";
    }
    protected db_project_info project = null;
    protected ProjectFiles_json files_json = null;
    protected boolean checkCurrentGroupAutorship() {
        if (!Current.getGroup().sender_address.equals(Current.getAccount().email)) {
            Log.Writeln_("Текущая группа " + Utils.Brackets(Current.getGroup().description)
                    + " принадлежит пользователю " + Utils.Brackets(Current.getGroup().sender_address)
                    + "\nВы не являетесь её автором!"
            );
            return false;
        } else return true;
    }
    protected boolean setProject() {
        if (Current.Check(Log, Current.Group, Current.Project) &&
                checkCurrentGroupAutorship() && checkSubdirectories()
                && UI.Question("Добавить текущий проект в глобальную базу тестов")) {
            project = Current.getProject();
            switch (project.languageName) {
                case fortran:
                    return passes.get(PassCode_2021.SPF_GetMaxMinBlockDistribution).Do();
                case c:
                    project.testMaxDim = Utils.getCProjectMaxDim(project);
                    return true;
                default:
                    return false;
            }
        }
        return false;
    }
    protected boolean checkSubdirectories() {
        if (Current.getProject().hasSubdirectories()) {
            Log.Writeln_("Запрещено добавлять тестовые проекты, содержащие подпапки!");
            return false;
        }
        return true;
    }
    protected boolean packPrograms() {
        files_json = project.filesToJson();
        if (files_json.files.isEmpty()) {
            Log.Writeln_("В проекте не найдено ни одной активной программы!");
            return false;
        }
        return true;
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        project = null;
        files_json = null;
        if (Current.getAccount().CheckRegistered(Log) && setProject() && packPrograms()) {
            target = new Test();
            target.genName();
            target.description = project.getLocalName() + " " + project.description;
            // target.project_description=project.description;
            target.dim = project.testMaxDim;
            target.date = new Date().getTime();
            target.sender_name = Current.getAccount().name;
            target.sender_address = Current.getAccount().email;
            target.group_id = Current.getGroup().id;
            target.files_json = Utils.jsonToPrettyFormat(Utils.gson.toJson(files_json));
            if (fillObjectFields()) {
                File src = Paths.get(System.getProperty("user.dir"), "Temp", target.id).toFile();
                Utils.forceDeleteWithCheck(src);
                FileUtils.forceMkdir(src);
                if (project.db.files.Data.isEmpty()) {
                    UI.Info("Клонируемый проект не синхронизирован!!! Внутренняя ошибка.");
                }
                project.Clone(src, false);
                FileUtils.copyFile(project.db.getFile(), Paths.get(src.getAbsolutePath(),
                        Constants.data, project.db.getFile().getName()).toFile());
                //архивация.
                File archive = Utils.getTempFileName("test_archive");
                if (passes.get(PassCode_2021.ZipFolderPass).Do(src.getAbsolutePath(), archive.getAbsolutePath())) {
                    target.project_archive_bytes = Utils.packFile(archive);
                    return true;
                }
            }
        }
        return false;
    }
    //тест с именем
    protected boolean fillObjectFields() throws Exception {
        return server.db.tests.ShowAddObjectDialog(target);
    }
    @Override
    protected void ServerAction() throws Exception {
        Command(new ServerExchangeUnit_2021(ServerCode.PublishObject, "", target));
    }
    @Override
    protected void performFinish() throws Exception {
        super.performFinish();
        passes.get(PassCode_2021.SynchronizeTests).Do();
    }
    @Override
    protected void showDone() throws Exception {
        super.showDone();
        server.db.tests.ui_.Show(target.getPK());
    }
}
