/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.transaction.monitor;

import com.sun.enterprise.admin.monitor.registry.*;
import com.sun.enterprise.admin.monitor.stats.*;
import com.sun.enterprise.admin.monitor.stats.JTAStats;
import javax.management.j2ee.statistics.*;

import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.Map;
import java.util.List;
import com.sun.logging.LogDomains;


public class JTAStatsImpl implements JTAStats, MonitoringLevelListener {

    private JTSMonitorMBean mBean = null;
    private GenericStatsImpl gStatsDelegate = null; 
    
    static Logger _logger = LogDomains.getLogger(LogDomains.JTA_LOGGER);
    private static JTAStatsImpl instance = null;

    // Will be instantiated by JTSMonitorMBean
    private JTAStatsImpl(JTSMonitorMBean mBean) {
        this.mBean = mBean;
        try {
            gStatsDelegate = new GenericStatsImpl("com.sun.enterprise.admin.monitor.stats.JTAStats",this);
        } catch (ClassNotFoundException clex) {
            _logger.log(Level.WARNING,"transaction.monitor.error_creating_jtastatsimpl",clex);
            // log and forget. Should not happen
        }
    }

    public static void createInstance(JTSMonitorMBean mBean) {
        if (instance == null)
            instance = new JTAStatsImpl(mBean);
    }
    public static JTAStatsImpl getInstance() {
        if (instance == null)
            throw new UnsupportedOperationException();
        return instance;
    }

    // Remove once it is deprecated
    public void setLevel(MonitoringLevel level) {
        if (level == MonitoringLevel.OFF) {
            mBean.stopMonitoring();
        }
        else if (level == MonitoringLevel.LOW || level == MonitoringLevel.HIGH) {
            mBean.startMonitoring();
        } 
    }

    // MonitoringLevelListener method
    public void changeLevel(MonitoringLevel from, MonitoringLevel to,
                            javax.management.j2ee.statistics.Stats handback) {
        if (from != to) {
            _logger.log(Level.FINE,"JTAStats Monitoring level changed from " + from + "  to  " + to);
            if (to == MonitoringLevel.OFF) {
                mBean.stopMonitoring();
            }
            else if (to == MonitoringLevel.LOW || to == MonitoringLevel.HIGH) {
                mBean.startMonitoring();
            }
        }
    }

    public StringStatistic getActiveIds() {
        String activeStr = null;
        try {
            activeStr = (String)mBean.getAttribute(JTSMonitorMBean.INFLIGHT_TRANSACTIONS);
        }catch (javax.management.AttributeNotFoundException jmxex) {
           _logger.log(Level.WARNING,"transaction.monitor.attribute_not_found",jmxex);
        }
        return new StringStatisticImpl(activeStr, 
                                      "ActiveIds", 
                                       //"getActiveIds", 
                                       "List", 
                                       "List of inflight transactions", 
                                       mBean.getStartTime(),
                                       System.currentTimeMillis()); 
    }

    public StringStatistic getState() {
        String str = null;
        try {
            str = (String)mBean.getAttribute(JTSMonitorMBean.IS_FROZEN);
        }catch (javax.management.AttributeNotFoundException jmxex) {
           _logger.log(Level.WARNING,"transaction.monitor.attribute_not_found",jmxex);
          // log and forget. Should not happen
        }
        
        return new StringStatisticImpl(str, 
                                       "State", 
                                       //"getState", 
                                       "String", 
                                       "Transaction system state: frozen?", 
                                       mBean.getStartTime(),
                                       System.currentTimeMillis()); 
    }

    public CountStatistic getActiveCount() {
        Integer count = null; 
        try {
            count = (Integer)mBean.getAttribute(JTSMonitorMBean.NUM_TRANSACTIONS_INFLIGHT); 
        }catch (javax.management.AttributeNotFoundException jmxex) {
           _logger.log(Level.WARNING,"transaction.monitor.attribute_not_found",jmxex);
          // log and forget. Should not happen
        }
        return new CountStatisticImpl(count.longValue(), 
                                      "ActiveCount", 
                                      // "getActiveCount", 
                                      CountStatisticImpl.DEFAULT_UNIT, 
                                      "number of active transactions", 
                                       System.currentTimeMillis(), 
                                       mBean.getStartTime());
    }

    public CountStatistic getCommittedCount() {
        Integer count = null; 
        try {
            count = (Integer)mBean.getAttribute(JTSMonitorMBean.NUM_TRANSACTIONS_COMPLETED); 
        }catch (javax.management.AttributeNotFoundException jmxex) {
           _logger.log(Level.WARNING,"transaction.monitor.attribute_not_found",jmxex);
          // log and forget. Should not happen
        }
        return new CountStatisticImpl(count.longValue(), 
                                      "CommittedCount", 
                                      //"getCommittedCount", 
                                      CountStatisticImpl.DEFAULT_UNIT, 
                                      "number of committed transactions", 
                                       System.currentTimeMillis(), 
                                       mBean.getStartTime());
    }

    public CountStatistic getRolledbackCount() {
        Integer count = null; 
        try {
            count = (Integer)mBean.getAttribute(JTSMonitorMBean.NUM_TRANSACTIONS_ROLLEDBACK); 
        }catch (javax.management.AttributeNotFoundException jmxex) {
           _logger.log(Level.WARNING,"transaction.monitor.attribute_not_found",jmxex);
          // log and forget. Should not happen
        }
        return new CountStatisticImpl(count.longValue(), 
                                      "RolledbackCount", 
                                      //"getRolledbackCount", 
                                      CountStatisticImpl.DEFAULT_UNIT, 
                                      "number of rolled-back transactions", 
                                       System.currentTimeMillis(), 
                                       mBean.getStartTime());
    }

    public void freeze() {
        mBean.freeze();
    }

    public void unfreeze() {
        mBean.unfreeze();
    }

	/**
	 * method for rolling back a single transaction
	 * @param txnId String representing the Id of the transaction to be
	 *				roled back
	 */
	public String rollback(String txnId) {
        String  result = (String) mBean.setRollback(txnId);
        if (_logger.isLoggable(Level.FINE))
		    _logger.log(Level.FINE, result);
        return result;
	}
		
	
    /**
	 public String[] rollback(String[] txnIds) {
        return mBean.rollback(txnIds);    
    }
	 */


    public Statistic getStatistic(String statisticName) {
        return gStatsDelegate.getStatistic(statisticName);
    }

    public String[] getStatisticNames() {
        return gStatsDelegate.getStatisticNames();
    }

    public Statistic[] getStatistics() {
        return gStatsDelegate.getStatistics();
    }

	public void changeLevel(MonitoringLevel from, MonitoringLevel to, MonitoredObjectType type) {
        if (from != to) {
            _logger.log(Level.FINE,"JTAStats Monitoring level changed from " + from + "  to  " + to);
            if (to == MonitoringLevel.OFF) {
                mBean.stopMonitoring();
            }
            else if (to == MonitoringLevel.LOW || to == MonitoringLevel.HIGH) {
                mBean.startMonitoring();
            }
        }
	}	

    public List<Map<String, String>> listActiveTransactions() {
        return mBean.listActiveTransactions();
    }
}
