/* UtilLib - Copyright (c) 2013-2016 Vincent Calame - Exemole
 * Logiciel libre donné sous triple licence :
 * 1) selon les termes de la CeCILL V2
 * 2) selon les termes de l’EUPL V.1.1
 * 3) selon les termes de la GNU GPLv3
 * Voir le fichier licences.txt
 */


package net.mapeadores.util.request;

import net.mapeadores.util.annotation.Nullable;


/**
 *
 * @author Vincent Calame
 */
public class OutputInfo {

    public final static short UNKNOWN_TYPE = 0;
    public final static short STREAM_TYPE = 1;
    public final static short JSON_TYPE = 2;
    public final static short PAGE_TYPE = 3;
    private final short type;
    private final String output;

    public OutputInfo(short type, String output) {
        if ((output != null) && (output.length() == 0)) {
            output = null;
        }
        this.type = type;
        this.output = output;
    }

    public static OutputInfo buildFromRequest(RequestMap requestMap) {
        return buildFromRequest(requestMap, null);
    }

    public static OutputInfo buildFromRequest(RequestMap requestMap, @Nullable String defaultPage) {
        String jsonType = requestMap.getParameter(RequestConstants.JSONTYPE_PARAMETER);
        if (jsonType != null) {
            return new OutputInfo(JSON_TYPE, requestMap.getParameter(RequestConstants.JSON_PARAMETER));
        }
        String json = requestMap.getParameter(RequestConstants.JSON_PARAMETER);
        if (json != null) {
            return new OutputInfo(JSON_TYPE, json);
        }
        String page = requestMap.getParameter(RequestConstants.PAGE_PARAMETER);
        if (page != null) {
            return new OutputInfo(PAGE_TYPE, page);
        }
        String stream = requestMap.getParameter(RequestConstants.STREAM_PARAMETER);
        if (stream != null) {
            return new OutputInfo(STREAM_TYPE, stream);
        }
        String output = requestMap.getParameter(RequestConstants.OUTPUT_PARAMETER);
        if (output != null) {
            int idx = output.indexOf('|');
            if (idx != -1) {
                short type = toType(output.substring(0, idx));
                if (type != UNKNOWN_TYPE) {
                    return new OutputInfo(type, output.substring(idx + 1));
                }
            }
        }
        if (defaultPage != null) {
            return new OutputInfo(PAGE_TYPE, defaultPage);
        }
        return new OutputInfo(UNKNOWN_TYPE, null);
    }

    private static short toType(String s) {
        if (s.equals("stream")) {
            return STREAM_TYPE;
        }
        if (s.equals("page")) {
            return PAGE_TYPE;
        }
        if (s.equals("json")) {
            return JSON_TYPE;
        }
        return UNKNOWN_TYPE;
    }

    public short getType() {
        return type;
    }

    public String getOutput() {
        return output;
    }

    public boolean hasOutput() {
        return (output != null);
    }

}
