package de.renew.draw.storables.impl.drawings;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import de.renew.draw.storables.ontology.Drawing;
import de.renew.ioontology.importing.ImportFormat;
import de.renew.ioontology.importing.ImportFormatHolder;
import de.renew.ioontology.importing.ImportFormatListener;

/**
 * Holds the Import formats of Renew and allows to register and deregister new formats.
 * The registered formats are also made available in the import menu.
 */
public class DrawingImportFormatHolder implements ImportFormatHolder<Drawing> {
    /**
     * Creates log4j Logger for this class to represent logging information.
     */
    private static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(DrawingImportFormatHolder.class);

    private static DrawingImportFormatHolder _instance;

    private final List<ImportFormat<Drawing>> _importFormats;

    private final List<ImportFormatListener<Drawing>> _importFormatListeners;

    /**
     * Constructs and sets up DrawingImportFormatHolder.
     */
    private DrawingImportFormatHolder() {
        super();
        _importFormats = new LinkedList<>();
        _importFormatListeners = new ArrayList<>();
    }

    /**
     * Singleton access method.
     *
     * @return The DrawingImportFormatHolder instance
     */
    public static DrawingImportFormatHolder getInstance() {
        if (_instance == null) {
            _instance = new DrawingImportFormatHolder();
        }
        return _instance;
    }

    /**
     * Adds an ImportFormat to Renew.
     * It is added to the known import formats and the import menus.
     *
     * @param importFormat the ImportFormat which is added to Renew
     */
    @Override
    public void addImportFormat(ImportFormat<Drawing> importFormat) {
        LOGGER.debug(getClass() + ": adding import format " + importFormat);
        _importFormats.add(importFormat);
        for (ImportFormatListener<Drawing> listener : _importFormatListeners) {
            listener.importFormatAdded(importFormat);
        }
    }

    @Override
    public void addImportFormatListener(ImportFormatListener<Drawing> listener) {
        _importFormatListeners.add(listener);
    }

    @Override
    public List<ImportFormat<Drawing>> getImportFormats() {
        return _importFormats;
    }

    /**
     * Removes an ImportFormat from Renew.
     * It is removed from the known import formats and the import menus.
     *
     * @param format the importFormat to be removed
     */
    @Override
    public void removeImportFormat(ImportFormat<Drawing> format) {
        _importFormats.remove(format);
        for (ImportFormatListener<Drawing> listener : _importFormatListeners) {
            listener.importFormatRemoved(format);
        }
    }

    @Override
    public void removeImportFormatListener(ImportFormatListener<Drawing> listener) {
        _importFormatListeners.remove(listener);
    }
}