/* FichothequeLib_Tools - Copyright (c) 2025 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.fichotheque.tools.importation.directory;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import net.fichotheque.importation.CorpusImport;
import net.fichotheque.tools.importation.Increment;
import net.fichotheque.xml.importation.CorpusImportXMLPart;
import net.mapeadores.util.exceptions.NestedIOException;
import net.mapeadores.util.exceptions.SwitchException;
import net.mapeadores.util.xml.AppendableXMLWriter;
import net.mapeadores.util.xml.XMLUtils;


/**
 *
 * @author Vincent Calame
 */
public final class CorpusImportSave {

    private CorpusImportSave() {

    }

    public static void save(CorpusImport corpusImport, File dir) {
        String type = corpusImport.getType();
        File initFile = new File(dir, "init.txt");
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(initFile), "UTF-8"))) {
            writer.write(corpusImport.getCorpus().getSubsetKeyString());
            writer.write("\n");
            writer.write(type);
        } catch (IOException ioe) {
            throw new NestedIOException(ioe);
        }
        switch (type) {
            case CorpusImport.EDIT_TYPE:
                saveEdit(corpusImport, dir);
                break;
            case CorpusImport.REMOVE_TYPE:
                throw new UnsupportedOperationException("No save on dir for remove type");
            default:
                throw new SwitchException("Unknown type: " + type);
        }
    }

    private static void saveEdit(CorpusImport corpusImport, File dir) {
        Increment increment = new Increment();
        for (CorpusImport.FicheImport ficheImport : corpusImport.getFicheImportList()) {
            if (!(ficheImport instanceof CorpusImport.EditFicheImport)) {
                continue;
            }
            StringBuilder buf = new StringBuilder();
            increment.appendTo(buf);
            buf.append(".xml");
            increment.increase();
            File f = new File(dir, buf.toString());
            try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8"))) {
                AppendableXMLWriter xmlWriter = XMLUtils.toXMLWriter(writer);
                xmlWriter.appendXMLDeclaration();
                CorpusImportXMLPart corpusImportXMLPart = new CorpusImportXMLPart(xmlWriter);
                corpusImportXMLPart.addEditFicheImport((CorpusImport.EditFicheImport) ficheImport);
            } catch (IOException ioe) {
                throw new NestedIOException(ioe);
            }
        }
    }

}
