package org.apache.slide.projector;

import java.util.Iterator;
import java.util.List;

import org.apache.slide.projector.constraints.ConstraintsManager;

public class ContentType {
    public final static String XML = "text/xml";
    public final static String HTML = "text/html";
    public final static String PLAIN_TEXT = "text/plain";
    public final static String TEXT = "text/*";
    public final static String DYNAMIC = "*";
    public final static String NULL = "projector/null";
    public static final String ARRAY = "array/*";
    public static final String DATE = "projector/date";
    public static final String LOCALE = "projector/locale";
    public static final String NUMBER = "number/*";
    public static final String URI = "text/uri";

    public static String getContentType(Object value) {
        return ConstraintsManager.getInstance().getContentType(value);
    }
    
    public static String determineContentType(String content) {
        if (content.indexOf("<html") != -1 ) {
            return HTML;
        } else if (content.startsWith("<?xml")) {
            return XML;
        } else {
            return PLAIN_TEXT;
        }
    }

    public static boolean determineIsDocument(String content) {
        if (determineContentType(content) == PLAIN_TEXT ) {
            return false;
        }
        return true;
    }

    public static boolean matches(String requiredContentType, String givenContentType) {
        if ( requiredContentType.equals(givenContentType) ) return true;
        if ( requiredContentType.equals(HTML) && givenContentType.equals(PLAIN_TEXT) ) return true;
        if ( requiredContentType.endsWith("*") && givenContentType.startsWith(requiredContentType.substring(0, requiredContentType.length()-1)) ) return true;
        return false;
    }

    public static boolean matches(String []allowedContentTypes, String givenContentType) {
        for ( int i = 0; i < allowedContentTypes.length; i++ ) {
            if ( matches(allowedContentTypes[i], givenContentType ) ) return true;
        }
        return false;
    }

    public static String getContentTypesAsString(List contentTypes) {
        StringBuffer buffer = new StringBuffer(256);
        boolean first = true;
        for ( Iterator i = contentTypes.iterator(); i.hasNext(); ) {
            if ( !first ) {
                buffer.append(", ");
            }
            first = false;
            buffer.append(i.next());
        }
        return buffer.toString();
    }

    public static String getContentTypesAsString(String[] contentTypes) {
        StringBuffer buffer = new StringBuffer(256);
        for ( int i = 0; i < contentTypes.length; i++ ) {
            if ( i > 0 ) {
                buffer.append(", ");
            }
            buffer.append(contentTypes[i]);
        }
        return buffer.toString();
    }
}