/*
 * 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.developersupport;

import com.redhat.persistence.engine.rdbms.*;

import java.sql.*;
import java.util.*;

/**
 * DeveloperSupportProfiler
 *
 * @author Rafael H. Schloming &lt;rhs@mit.edu&gt;
 * @version $Revision: #4 $ $Date: 2004/04/07 $
 **/

public class DeveloperSupportProfiler implements RDBMSProfiler {

    public final static String versionId = "$Id: //core-platform/dev/src/com/arsdigita/developersupport/DeveloperSupportProfiler.java#4 $ by $Author: dennis $, $DateTime: 2004/04/07 16:07:11 $";

    public DeveloperSupportProfiler() {}

    public StatementLifecycle getLifecycle(RDBMSStatement stmt) {
        if (DeveloperSupport.getListenerCount() > 0) {
            return new Lifecycle(stmt);
        } else {
            return null;
        }
    }

    private class Lifecycle implements StatementLifecycle {

        private RDBMSStatement m_stmt;
        private long m_start;
        private HashMap m_bindings = new HashMap();

        public Lifecycle(RDBMSStatement stmt) {
            m_stmt = stmt;
        }

        public void beginPrepare() {}
        public void endPrepare() {}
        public void endPrepare(SQLException e) {}

        public void beginSet(int pos, int type, Object obj) {
            m_bindings.put(new Integer(pos), obj);
        }

        public void endSet() {}
        public void endSet(SQLException e) {}

        public void beginExecute() {
            m_start = System.currentTimeMillis();
        }

        public void endExecute(int updateCount) {
            endExecute(null);
        }

        public void endExecute(SQLException e) {
            long end = System.currentTimeMillis();
            DeveloperSupport.logQuery
                (System.identityHashCode(DeveloperSupportProfiler.this),
                 (m_stmt.getSignature() == null
                  ? "executeUpdate" : "executeQuery"),
                 m_stmt.getText(), m_bindings, end - m_start, e);
        }

        public void beginNext() {}
        public void endNext(boolean more) {}
        public void endNext(SQLException e) {}

        public void beginGet(String column) {}
        public void endGet(Object result) {}
        public void endGet(SQLException e) {}

        public void beginClose() {}
        public void endClose() {}
        public void endClose(SQLException e) {}

    }

}
