/*
 * Scone - The Web Enhancement Framework
 * Copyright (C) 2009 Harald Weinreich, Volkert Buchmann, Frank Wollenweber, Torsten Haß
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
package scone.accesstracking2;

import java.util.Date;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

import scone.netobjects.Access;
import scone.netobjects.AccessCache;
import scone.netobjects.AccessEvent;
import scone.netobjects.NetNode;
import scone.netobjects.NetNodeCache;

import com.ibm.wbi.Editor;
import com.ibm.wbi.RequestEvent;
import com.ibm.wbi.RequestRejectedException;
import com.ibm.wbi.protocol.http.DocumentInfo;
import com.ibm.wbi.protocol.http.HttpRequestHeader;
import com.ibm.wbi.protocol.http.HttpResponseHeader;


/**
 * This meg creates the user logging entries in the access database for non-html documents...<P>
 *
 * @author Harald Weinreich, Torsten Hass
 * @version 0.9, 11/26/2002
 */
public class NoHTMLAccessMeg extends Editor {

    private scone.Plugin plugin = null;
    private DocumentInfo documentInfo;
    private HttpRequestHeader  request;
    private HttpResponseHeader response;
    private String       uriString;
    private String       nodeId = "";           // NodeId of the current object.
    private String       frame = "";            // Name of this frame
    private String       referrerUriString = ""; // Uri of the referrer
    private String       referrerNodeId = "";   // NodeId of the referrer
    private String       id = "0";              // User id=0 means unknown user...
    private String       accessStatus = "";
    private String       mimeType = "";
    private String       size = "";
    private long         start;
    private long         lastModified;

    public NoHTMLAccessMeg(scone.Plugin plugin) {
        this.plugin = plugin;
    }

    public void handleRequest(RequestEvent e) throws RequestRejectedException {

        documentInfo = (DocumentInfo) e.getRequestInfo(); // get RequestInfo
        request = documentInfo.getHttpRequestHeader();  // Get the request header
        response = documentInfo.getHttpResponseHeader(); // Get the response header
        mimeType = response.get("Content-Type") == null
                ? ""
                : response.get("Content-Type");
        if (mimeType.equals("")
                || (               // List Mime types that shall be traced!
                           !mimeType.equals("application/excel")
                        && !mimeType.equals("application/msword")
                        && !mimeType.equals("application/rtf")
                        && !mimeType.equals("text/rtf")
                        && !mimeType.equals("application/pdf")
                        && !mimeType.equals("application/postscript")
                        && !mimeType.equals("application/powerpoint")
                        && !mimeType.equals("application/zip"))) {
            throw new RequestRejectedException();
        }

        // System.out.println("#"+mimeType+"#");

        referrerUriString = request.get("Referer");           // Get Refer(r)er
        uriString = request.getUrl();                 // get URL

        accessStatus = response.getCode() == null ? "-1" : response.getCode();
        size = response.get("Content-Length") == null
                ? "-1"
                : response.get("Content-Length");
        try {
            lastModified = response.get("Last-Modified") == null
                    ? -1L
                    : parseDate(response.get("Last-Modified")).getTime();
        } catch (NumberFormatException ex) {
            lastModified = -1L;
        }

        start = new Date().getTime();

        NetNode node = NetNodeCache.get(uriString);

        nodeId = node.getNodeId();
        if (nodeId == null || nodeId.length() == 0) {
            nodeId = "0";
        }   // was it available?

        // set node parameters
        node.setMimeType(mimeType);
        node.setAccessStatus(accessStatus);
        node.setLastModified(lastModified);

        if (referrerUriString != null) {
            node = NetNodeCache.get(referrerUriString);
            referrerNodeId = node.getNodeId();
            if (referrerNodeId == null || referrerNodeId.length() == 0) {
                referrerNodeId = "0";
            }   // was it available?
        } else {
            referrerNodeId = "0";
        }            

        // Create new access object
        Access a = AccessCache.get(id, nodeId, start, "No Frame");

        a.setReferrerNodeId(referrerNodeId);

        AccessCache.broadcastEvent(new AccessEvent(a));  // Has to be done!

        a.store();

        // System.out.println("Access to non-html-File!");

        throw new RequestRejectedException();
    }

    private Date parseDate(String dateString) {
        SimpleDateFormat formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        ParsePosition pos = new ParsePosition(0);
        formatter.setTimeZone(TimeZone.getDefault());
        // formatter.setTimeZone(TimeZone.getTimeZone("GMT+01:00"));
        return formatter.parse(dateString, pos);
    }

}
