/*
Copyright (C) 2000-2010  Ministere de la culture et de la communication (France), AJLSM
See LICENCE file
*/
/*
 * Created by IntelliJ IDEA.
 * User: fglorieux
 * Date: 24 sept. 2002
 * Time: 21:25:14
 * To change template for new class use
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package fr.gouv.culture.sdx.sitemap;

import fr.gouv.culture.sdx.application.Application;
import fr.gouv.culture.sdx.document.BinaryDocument;
import fr.gouv.culture.sdx.document.Document;
import fr.gouv.culture.sdx.documentbase.DocumentBase;
import fr.gouv.culture.sdx.exception.SDXException;
import fr.gouv.culture.sdx.framework.Framework;
import fr.gouv.culture.sdx.framework.FrameworkImpl;
import fr.gouv.culture.sdx.utils.Utilities;
import fr.gouv.culture.sdx.utils.configuration.ConfigurationUtils;
import fr.gouv.culture.sdx.utils.constants.Node;
import org.apache.avalon.framework.service.ServiceManager;
import org.apache.avalon.framework.service.Serviceable;
import org.apache.avalon.framework.parameters.Parameters;
import org.apache.cocoon.ProcessingException;
import org.apache.cocoon.environment.ObjectModelHelper;
import org.apache.cocoon.environment.Request;
import org.apache.cocoon.environment.Response;
import org.apache.cocoon.environment.SourceResolver;
import org.apache.cocoon.reading.AbstractReader;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.Map;

public class DocumentReader extends AbstractReader implements Serviceable {

    // could implement Cacheable

    private ServiceManager manager;
    private DocumentBase base;
    private Document doc;
//    FIXME : private fields never used locally [MP]
    private Response response;
    private Request request;

    public void service(ServiceManager manager) {
        this.manager = manager;
    }

    public void setup(SourceResolver resolver, Map map, String src, Parameters par)
            throws ProcessingException, SAXException, IOException {

        super.setup(resolver, map, src, par);
        // can't get a response and a acceptRequest by this way (copy/paste from other readers)
        try {
            this.response = ObjectModelHelper.getResponse(map);
            this.request = ObjectModelHelper.getRequest(map);
        } catch (Exception e) {
            // getLog().error("can't get response or acceptRequest", e);
        }
        //our framework object
        FrameworkImpl frame = null;
        try {
            ConfigurationUtils.checkServiceManager(this.manager);
            // TODO, support remote ?
            String appId = par.getParameter(Node.Name.APP, null);
            String appPath = par.getParameter(Node.Name.APPBYPATH, null);
            String baseId = par.getParameter(Node.Name.BASE, null);
            String id = par.getParameter(Node.Name.ID, null);
            String attid = par.getParameter(Node.Name.ATTID, null);
            if (Utilities.checkString(attid))
                id = Utilities.attId(id, attid);

            /*
            String type=par.getParameter("type", null);
            */

            // TODOException?: better handling of exceptions
            frame = (FrameworkImpl) this.manager.lookup(Framework.ROLE);
            if (frame != null) {
                Application app = frame.getApplicationById(appId);
                if ( app == null ) app = frame.getApplicationByPath(appPath);
                if (app != null) {
                    if (baseId != null && !"".equals(baseId))
                        this.base = app.getDocumentBase(baseId);
                    else
                        this.base = app.getDefaultDocumentBase();
                    this.doc = new BinaryDocument(id, null, null);
                }
            }
        } catch (Exception e) {
            // getLog().error("can't get parameter", e);
        } finally {
            if (frame != null) manager.release(frame);
        }

    }

    /**
     * Get the mime-type of the output of this <code>Serializer</code>
     * This default implementation returns null to indicate that the
     * mime-type specified in the sitemap is to be used
     */
    public String getMimeType() {
        String out = null;
        if (base != null)
            try {
                out = base.getMimeType(doc);
            } catch (SDXException e) {
                // log ?
            }
        return out;
    }

    public void generate()
            throws IOException, ProcessingException {

        if (out == null) {
            // getLog().debug("pas d'outputStream");
        }
        if (base == null) {
            // getLog().debug("pas de base");
        }

        try {
            // need to set mime type of response (when we will get it)
/*
            final long expires = parameters.getParameterAsInteger("expires", -1);

            if (expires > 0) {
                response.setDateHeader("Expires", System.currentTimeMillis() + expires);
            }

            long contentLength = this.inputSource.getContentLength();
            if (contentLength != -1) {
                // FIXME (VG): Environment has setContentLength, and
                // Response interface has not. Strange.
                response.setHeader("Content-Length", String.valueOf(contentLength));
            }
            response.setHeader("Accept-Ranges", "bytes");
*/
            if (this.base != null) {
                this.base.getDocument(this.doc, out);
                out.flush();
            }
        } catch (Exception e) {
            // getLog().error("SDXException", e);
            ;
        }

    }

    /**
     * Recycle the service
     */
    /*public void recycle() {
       super.recycle();
       this.base = null;
       this.doc = null;
       this.manager = null;
       this.acceptRequest = null;
       this.response = null;
    }
    */


}
