package dendrarium.commandline;

import dendrarium.core.entities.TaskBusinessProcess;
import dendrarium.portal.Download;
import dendrarium.trees.xml.ForestExportFormat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.hibernate.Session;

/**
 *
 * @author pta
 */
public class ExportAll {

    private Session session;

    public ExportAll(Session session) {
        this.session = session;
    }


    public void exportAll(String directory) {
        Iterator<TaskBusinessProcess> accepted = session.getNamedQuery("accepted").iterate();
        Download download = new Download();

        while (accepted.hasNext()) {
            TaskBusinessProcess task = accepted.next();
            try {
                String sent_id = task.getTask().getSent_id();

                System.out.println("Eksport zdania " + sent_id);

                byte[] data = download.writeAnswer(task.getSuperAnswer(), ForestExportFormat.FULL);
                int index = sent_id.lastIndexOf("/");
                String dir = directory + "/" + sent_id.substring(0, index);
                String filename = sent_id.substring(index + 1) + ".xml";
                new File(dir).mkdirs();
                new File(dir).mkdirs();
                OutputStream out = null;
                try {
                    out = new FileOutputStream(new File(dir + "/" + filename));
                    out.write(data);
                }
                finally {
                    if(out != null) {
                        out.close();
                    }
                }
                
            } catch (Exception ex) {
                Logger.getLogger(ExportAll.class.getName()).log(Level.SEVERE, null, ex);
                break;
            }
        }
    }

}
