// PutedEntry.java
// $Id: PutedEntry.java,v 1.3 1997/07/30 13:59:40 ylafon Exp $  
// (c) COPYRIGHT MIT and INRIA, 1997.
// Please first read the full copyright statement in file COPYRIGHT.html

package w3c.jigsaw.filters;

import java.io.*;
import java.util.*;

import w3c.jigsaw.auth.AuthFilter;
import w3c.tools.store.*;
import w3c.jigsaw.http.*;
import w3c.www.http.*;
import w3c.jigsaw.resources.*;

/**
 * We want free pickling, hence the super class.
 */

public class PutedEntry extends AttributeHolder {
    protected static int ATTR_AUTHOR   = -1;
    protected static int ATTR_URL      = -1;
    protected static int ATTR_FILENAME = -1;
    protected static int ATTR_TIME     = -1;

    static {
	Class c = null;
	Attribute a = null;
    
	try {
	    c = Class.forName("w3c.jigsaw.filters.PutedEntry");
	} catch (Exception ex) {
	    ex.printStackTrace();
	    System.exit(1);
	}
	// The author of change:
	a = new StringAttribute("author"
				, null
				, Attribute.EDITABLE);
	ATTR_AUTHOR = AttributeRegistry.registerAttribute(c, a);
	// The mandatory url:
	a = new StringAttribute("url"
				, null
				, Attribute.EDITABLE);
	ATTR_URL = AttributeRegistry.registerAttribute(c, a);
	// The optional absolute file name:
	a = new StringAttribute("filename"
				, null
				, Attribute.EDITABLE);
	ATTR_FILENAME = AttributeRegistry.registerAttribute(c, a);
	// The time of modification:
	a = new LongAttribute("time"
			      , null
			      , Attribute.EDITABLE);
	ATTR_TIME = AttributeRegistry.registerAttribute(c, a);
    }

    final String getAuthor() {
	return getString(ATTR_AUTHOR, null);
    }

    final String getURL() {
	return getString(ATTR_URL, null);
    }

    final String getFilename() {
	return getString(ATTR_FILENAME, null);
    }

    final long getTime() {
	return getLong(ATTR_TIME, -1);
    }

    final String getKey() {
	String key = getFilename();
	if ( key == null )
	    return getURL();
	return key;
    }

    synchronized void update(Request request) {
	String author = (String) request.getState(AuthFilter.STATE_AUTHUSER);
	long   time   = System.currentTimeMillis();
	setValue(ATTR_AUTHOR, author);
	setValue(ATTR_TIME, new Long(time));
    }

    static PutedEntry makeEntry(Request request) {
	HTTPResource r = (HTTPResource) request.getTargetResource();
	if ( r != null ) {
	    // Build an entry:
	    PutedEntry e = new PutedEntry();
	    e.setValue(ATTR_URL, request.getURL().toExternalForm());
	    if ( r instanceof FileResource )
		e.setValue(ATTR_FILENAME
			   , ((FileResource) r).getFile().getAbsolutePath());
	    // Update other infos:
	    e.update(request);
	    return e;
	}
	return null;
    }

}

