package de.renew.lola2.io;

import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import de.renew.draw.storables.ontology.Drawing;
import de.renew.ioontology.importing.ImportFormatAbstract;
import de.renew.lola2.LolaFileFilter;
import de.renew.lola2.parser.LolaParser;


/**
 * This class implements the Lola import format.
 * It is used to import Lola net files into the application.
 * The imported file can be used for further processing in Lola.
 */
public class LolaImportFormat extends ImportFormatAbstract<Drawing> {
    /**
     * The name of the Lola import format.
     * This is used to identify the format when importing files.
     */
    public static final String FORMAT_NAME = "Lola net file";
    private static org.apache.log4j.Logger _logger =
        org.apache.log4j.Logger.getLogger(LolaImportFormat.class);

    /**
     * Constructor for LolaImportFormat.
     */
    public LolaImportFormat() {
        super(FORMAT_NAME, new LolaFileFilter());
    }

    @Override
    public List<Drawing> importFiles(URL[] paths) throws Exception {
        _logger.info("[Lola] Lola Import: Starting");
        List<Drawing> result = null;
        if (paths != null) {
            List<Drawing> drawings = new ArrayList<Drawing>();
            _logger.info("[Lola] Lola Import: Importing file " + paths[0].toString());
            drawings.set(0, importFile(paths[0]));
            result = drawings;
        }
        assert (result != null) : "Failure in LolaImportFormat: result == null";
        return result;
    }

    /**
     * Imports a Lola net file from the given URL.
     *
     * @param file the URL of the Lola net file to import
     * @return a Drawing object representing the imported Lola net
     * @throws Exception if an error occurs during import
     */
    public Drawing importFile(URL file) throws Exception {
        Drawing result = null;
        if (file != null) {
            FileInputStream stream = new FileInputStream(new File(file.getFile()));
            result = new LolaParser().importNet(stream);
            stream.close();
        }
        assert (result != null) : "Failure in LolaImportFormat: result == null";
        return result;
    }
}