package de.renew.io.importFormats;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import de.renew.draw.storables.ontology.Drawing;
import de.renew.gui.pnml.PNMLFormat;
import de.renew.io.FileFilterCreator;
import de.renew.ioontology.importing.ImportFormatAbstract;

/**
 * Implementation of ImportFormat for PNML files.
 */
public class PNMLImportFormat extends ImportFormatAbstract<Drawing> {
    /**
     * Decides whether Imported PNML is correctly formatted.
     */
    public PNMLImportFormat() {
        super("PNML", FileFilterCreator.createPNMLFileFilter());
    }


    @Override
    public List<Drawing> importFiles(URL[] files) throws Exception {
        List<Drawing> list = new ArrayList<>();
        if (files != null) {
            for (URL file : files) {
                list.addAll(importFile(file));
            }
        }
        return list;
    }

    /**
     * Returns a list of all drawings in the file.
     * @param file the PNML file to be imported.
     * @return Enumeration, list of all imported drawings.
     * @throws Exception is thrown in case of failure during import of file.
     */
    protected List<Drawing> importFile(URL file) throws Exception {
        if (file == null) {
            return Collections.emptyList();
        }

        InputStream stream = file.openStream();
        PNMLFormat format = new PNMLFormat();
        List<Drawing> result = format.parse(stream);
        stream.close();
        return result;
    }

    /**
     * Returns a list of all drawings in the file.
     * @param src the PNML file to be imported.
     * @return Enumeration, list of all imported drawings.
     * @throws Exception is thrown in case of failure during import of file.
     */
    public List<Drawing> importFile(String src) throws Exception {
        if (src == null || src == "") {
            return Collections.emptyList();
        }

        PNMLFormat format = new PNMLFormat();
        return format.parse(new ByteArrayInputStream(src.getBytes()));
    }
}