/*
 * Copyright 2006-2007 Queplix Corp.
 *
 * Licensed under the Queplix Public License, Version 1.1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.queplix.com/solutions/commercial-open-source/queplix-public-license/
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 *
 */

package com.queplix.core.modules.eqlext.www;

import com.queplix.core.integrator.security.LogonSession;
import com.queplix.core.integrator.security.WebLoginManager;
import com.queplix.core.modules.eql.ejb.HistoryLocal;
import com.queplix.core.modules.eql.ejb.HistoryLocalHome;
import com.queplix.core.modules.eqlext.ejb.GetRecordsLocal;
import com.queplix.core.modules.eqlext.ejb.GetRecordsLocalHome;
import com.queplix.core.modules.eqlext.jxb.gr.Reqs;
import com.queplix.core.modules.eqlext.jxb.gr.ResField;
import com.queplix.core.modules.eqlext.jxb.gr.Ress;
import com.queplix.core.utils.JNDINames;
import com.queplix.core.utils.www.AbstractServlet;
import com.queplix.core.utils.www.ServletHelper;
import com.queplix.core.utils.xml.XMLHelper;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * History formatter servlet.
 * <strong>USAGE</strong>: <pre>POST /getHistory[/asText|/asHTML]
 * <?xml version="1.0" encoding="UTF-8"?>
 * <reqs>...</reqs>
 * </pre>
 * <p><strong>Parameters</strong>:
 * <p>     One of:
 * <p>        NULL: default transformation
 * <p>     or..
 * <p>        asText: transform to plain text
 * <p>     or..
 * <p>        asHTML: transform to HTML
 * </p>
 *
 * @author [ALB] Baranov Andrey
 * @version $Revision: 1.1.1.1 $ $Date: 2005/09/12 15:30:45 $
 */

public class HistoryFormatterServlet
        extends AbstractServlet {

    // ----------------------------------------------------- constants

    private static final int MODE_UNKNOWN = -1;
    private static final int MODE_TEXT = 0;
    private static final int MODE_HTML = 1;

    private static final String AS_TEXT = "asText";
    private static final String AS_HTML = "asHTML";

    // ----------------------------------------------------- service method

    public void service(HttpServletRequest request,
                        HttpServletResponse response)
            throws IOException, ServletException {

        // Initialization
        LogonSession ls = null;
        try {
            ls = WebLoginManager.getLogonSession(request);
        } catch (Exception ex) {
            throw new ServletException(ex);
        }
        request.setCharacterEncoding("UTF-8");

        GetRecordsLocal getRecordsLocal = (GetRecordsLocal)
                getLocalObject(JNDINames.GetRecords, GetRecordsLocalHome.class);

        HistoryLocal historyLocal = (HistoryLocal)
                getLocalObject(JNDINames.History, HistoryLocalHome.class);

        // Get mode
        int mode;
        String pathInfo = request.getPathInfo();
        if(pathInfo != null && pathInfo.indexOf(AS_TEXT) >= 0) {
            mode = MODE_TEXT;
        } else if(pathInfo != null && pathInfo.indexOf(AS_HTML) >= 0) {
            mode = MODE_HTML;
        } else {
            mode = MODE_UNKNOWN;
        }

        if(logger.getLogger().isDebugEnabled()) {
            logger.DEBUG("History formatter servlet:");
            logger.DEBUG("   mode: " + mode);
        }

        String formattedHistory = null;
        boolean isHTMLMode = false;

        try {
            // Requesting GetRecords.
            Reqs reqs = (Reqs) XMLHelper.getParsedObject(Reqs.class,
                    request.getInputStream());

            // Gettting response.
            Ress ress = getRecordsLocal.process(reqs, ls).getRess();

            if(ress.getRows() == 1) {
                ResField historyResField = ress.getRes().getResRecord(0)
                        .getResField(0);
                String history = historyResField.getResFieldValue();

                switch(mode) {
                    case MODE_TEXT:
                        isHTMLMode = false;
                        break;
                    case MODE_HTML:
                        isHTMLMode = true;
                        break;
                    default:
                        isHTMLMode = historyLocal.isHistoryValid(history);
                }

                if(isHTMLMode) {
                    formattedHistory = historyLocal.toHTML(history);
                } else {
                    formattedHistory = historyLocal.toText(history);
                }
            }

        } catch (Exception ex) {
            throw new ServletException(ex);
        }

        // Printitng out.
        response.setHeader("Cache-Control", "no-cache");
        response.setHeader("Pragma", "no-cache");
        response.setContentType(isHTMLMode ? ServletHelper.CONTENT_TYPE_HTML
                :ServletHelper.CONTENT_TYPE_TEXT);

        if(formattedHistory != null) {
            response.getWriter().print(formattedHistory);
        }

    } // end of service()

} // end of class
