/*
 * @(#)MagicRecognizer.java  1.0  2011-08-18
 * 
 * Copyright (c) 2011 Werner Randelshofer, Immensee, Switzerland.
 * All rights reserved.
 * 
 * You may not use, copy or modify this file, except in compliance with the
 * license agreement you entered into with Werner Randelshofer.
 * For details see accompanying license terms.
 */
package ch.randelshofer.activation;

import java.io.UnsupportedEncodingException;

/**
 * {@code MagicRecognizer}.
 *
 * @author Werner Randelshofer
 * @version 1.0 2011-08-18 Created.
 */
public class MagicRecognizer implements Recognizer {
    /** This array contains magics and mime types. */
    private Object[][] magics = {
        {asciiMagic("LPF "),"video/lpf"}
    };
    private final static MagicRecognizer instance = new MagicRecognizer();
public static MagicRecognizer getInstance() {
        return instance;
    }    
    
    private static int asciiMagic(String str) {
        try {
        byte[] b= str.getBytes("ASCII");
        return (b[0]<<24)|((b[1]&0xff)<<16)|((b[2]&0xff)<<8)|(b[3]&0xff);
        } catch (UnsupportedEncodingException ex) {
            throw new InternalError("ASCII is not installed");
        }
    }
    
    @Override
    public int getMinimalDeterminableDataLength() {
        return 4;
    }

    @Override
    public String getContentType(byte[] b) {
        int magic=(b[0]<<24)|((b[1]&0xff)<<16)|((b[2]&0xff)<<8)|(b[3]&0xff);
    
        // FIXME use a hash map!
        for (int i=0;i<magics.length;i++) {
            if (((Integer)magics[i][0])==magic) return (String)magics[i][1];
        }
        
        return "application/octet-stream";
    }
    
}
