/*
 * Copyright (C) 2003-2004 Red Hat Inc. All Rights Reserved.
 *
 * The contents of this file are subject to the CCM Public
 * License (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.redhat.com/licenses/ccmpl.html.
 *
 * Software distributed under the License is distributed on an
 * "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
 * or implied. See the License for the specific language
 * governing rights and limitations under the License.
 *
 */
package com.arsdigita.versioning;

import com.arsdigita.persistence.OID;

import org.apache.log4j.Logger;

/**
 * This is for debugging.
 * 
 * @author Vadim Nasardinov (vadimn@redhat.com)
 * @since  2003-05-28
 * @version $Revision: #4 $ $Date: 2004/04/07 $
 **/
public final class LoggingListener extends RollbackAdapter {
    private final static Logger s_log = Logger.getLogger(LoggingListener.class);

    private boolean m_isOn = true;
    private boolean m_useLog4j = false;
    private String m_msg;

    public LoggingListener(String msg) {
        m_msg = msg;
    }


    public void onStart(OID oid) {
        log(m_msg + " onStart: ", oid);
    }

    public void onEnqueue(OID oid) {
        log("onEnqueue: ", oid);
    }

    public void onSet(OID oid, String property, Object value) {
        log("onSet: ", oid, property, value);
    }

    public void onAdd(OID oid, String property, Object value) {
        log("onAdd: ", oid, property, value);
    }

    public void onRemove(OID oid, String property, Object value) {
        log("onRemove: ", oid, property, value);
    }

    public void onDequeue(OID oid) {
        log("onDequeue: ", oid);
    }

    public void onFinish(OID oid) {
        log(m_msg + " onFinish: ", oid);
    }

    private void log(String msg) {
        if ( !m_isOn) return;

        if ( m_useLog4j ) {
            s_log.debug(msg);
        } else {
            System.err.println(msg);
        }
    }

    private void log(String msg, OID oid) {
        StringBuffer sb = new StringBuffer(200);
        sb.append(msg).append("oid=").append(Adapter.serialize(oid));
        log(sb.toString());
    }

    private void log(String msg, OID oid, String property, Object value) {
        StringBuffer sb = new StringBuffer(200);
        sb.append(msg).append("oid=").append(Adapter.serialize(oid));
        sb.append(", property=").append(property);
        log(sb.toString());
    }
}
