/*
 * Copyright (C) 2009  Trustin Heuiseung Lee
 *
 * This is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; either version 2.1 of
 * the License, or (at your option) any later version.
 *
 * This software is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this software; if not, write to the Free
 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
 */

// Derived from Michael Meiwald's PNM decoder:
// http://www.mms-computing.co.uk/uk/co/mmscomputing/imageio/ppm/
package net.gleamynode.imageio.pnm;

import java.io.IOException;
import java.util.Locale;

import javax.imageio.ImageReader;
import javax.imageio.spi.ImageReaderSpi;
import javax.imageio.stream.ImageInputStream;

public class PortableAnymapImageReaderSpi extends ImageReaderSpi {

    private static final String[] NAMES = {
        "pnm", "PNM", "pbm", "PBM", "pgm", "PGM", "ppm", "PPM"
    };

    private static final String[] MIME_TYPES = {
        "image/pnm", "image/pbm", "image/pgm", "image/ppm"
    };

    public PortableAnymapImageReaderSpi() {
        super(
                "Trustin Lee, http://gleamynode.net/", "1.0",
                NAMES, NAMES, MIME_TYPES, PortableAnymapImageReader.class.getName(),
                STANDARD_INPUT_TYPE, null, false, null, null, null, null,
                false, null, null, null, null);
    }

    @Override
    public ImageReader createReaderInstance(Object extension) throws IOException {
        return new PortableAnymapImageReader(this);
    }

    @Override
    public boolean canDecodeInput(Object source) throws IOException {
        if (!(source instanceof ImageInputStream)) {
            return false;
        }
        ImageInputStream stream = (ImageInputStream) source;
        int type;
        try {
            stream.mark();
            type = stream.readShort() & 0xffff;
            stream.reset();
        } catch (IOException e) {
            return false;
        }

        switch (type) {
        case PortableAnymapImageReader.TYPE_PBM_RAW:
        case PortableAnymapImageReader.TYPE_PGM_RAW:
        case PortableAnymapImageReader.TYPE_PPM_RAW:
            return true;
        default:
            return false;
        }
    }

    @Override
    public String getDescription(Locale locale) {
        return "PNM (Portable Anymap) Image Reader";
    }
}