/* BdfServer_JsonProducers - Copyright (c) 2012-2022 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 fr.exemole.bdfserver.jsonproducers.administration;

import fr.exemole.bdfserver.api.BdfServer;
import fr.exemole.bdfserver.tools.docstream.DocStreamFactory;
import java.io.IOException;
import java.net.URI;
import net.mapeadores.util.io.DocStream;
import net.mapeadores.util.json.JSONWriter;
import net.mapeadores.util.json.JsonProperty;


/**
 *
 * @author Vincent Calame
 */
public class StreamTextJsonProperty implements JsonProperty {

    private final BdfServer bdfServer;
    private final URI uri;
    private String path;
    private String extension = "";

    public StreamTextJsonProperty(BdfServer bdfServer, URI uri) {
        this.bdfServer = bdfServer;
        this.uri = uri;
        path = uri.getPath();
        if ((path == null) || (path.length() == 1)) {
            throw new IllegalArgumentException("uri.getPath is null");
        }
        path = path.substring(1);
        int idx = path.lastIndexOf('.');
        if (idx != -1) {
            extension = path.substring(idx + 1);
        }
    }

    @Override
    public String getName() {
        return "streamText";
    }

    @Override
    public void writeValue(JSONWriter jw) throws IOException {
        jw.object();
        {
            jw.key("extension")
                    .value(extension);
            jw.key("path")
                    .value(path);
            jw.key("content")
                    .value(getBdfResourceContent());
        }
        jw.endObject();
    }

    private String getBdfResourceContent() {
        DocStream docStream = DocStreamFactory.buildDocStream(bdfServer, uri);
        if (docStream == null) {
            return "";
        }
        return docStream.getContent();
    }

}
