package _VisualDVM.Passes.All;
import Common.Utils.Utils_;
import _VisualDVM.ComponentsServer.Component.Sapfor.Sapfor;
import _VisualDVM.ComponentsServer.Component.Sapfor.TransformationPermission;
import _VisualDVM.Passes.PassCode;
import _VisualDVM.Passes.Sapfor.Transformation;
import _VisualDVM.ProjectData.Files.DBProjectFile;
import _VisualDVM.ProjectData.Files.FileType;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Vector;
public class PrepareForModulesAssembly extends Transformation {
    @Override
    protected PassCode necessary() {
        return PassCode.SPF_GetIncludeDependencies;
    }
    @Override
    protected boolean canStart(Object... args) throws Exception {
        switch (Sapfor.transformationPermission) {
            case All:
                return super.canStart(args) && target.CheckSameStyle(Log);
            case VariantsOnly:
                if (getPermission().equals(TransformationPermission.VariantsOnly)) {
                    return super.canStart(args) && target.CheckSameStyle(Log);
                } else {
                    Log.Writeln_("Разрешено только построение параллельных вариантов!");
                    return false;
                }
            case None:
                Log.Writeln_("Нет разрешения на выполнение преобразований");
                return false;
        }
        return false;
    }
    @Override
    protected void body() throws Exception {
        File total = Paths.get(target.last_version.Home.getAbsolutePath(), "total.for").toFile();
        while (total.exists()) {
            total = Paths.get(target.last_version.Home.getAbsolutePath(), Utils_.getDateName("total") + ".for").toFile();
            Thread.sleep(1000);
        }
        //--создать
        Vector<String> total_lines = new Vector<>();
        for (String name : target.files_order) {
            total_lines.add("      include " + Utils_.Quotes(Utils_.toU(name)));
        }
        FileUtils.writeLines(total, total_lines, false);
        //-------------------------------
        //скопировать все файлы
        for (String name : target.db.files.Data.keySet()) {
            Files.copy(
                    target.db.files.Data.get(name).file.toPath(),
                    Paths.get(target.last_version.Home.getAbsolutePath(), name)
            );
        }
    }
    @Override
    protected void performDone() throws Exception {
        super.performDone();
        //--->>>
        target.last_version.Open();
        target.last_version.db.BeginTransaction();
        for (String name : target.files_order) {
            DBProjectFile file = target.last_version.db.files.get(name);
            file.fileType = FileType.header;
            target.last_version.db.Update(file);
        }
        target.last_version.db.Commit();
        target.last_version.Close();
    }
}
