package com.nms.server.thread;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.Future;

import org.apache.log4j.Logger;

import com.nms.server.common.Common;
import com.nms.server.common.Constants;
import com.nms.server.dao.CommonDao;

public class DetecSelfThread implements Runnable{
	private  Logger logger = Logger.getLogger(DetecSelfThread.class);
	
	public DetecSelfThread(){
		
	}
	
	@Override
	public void run() {
//		Thread.currentThread().setName("DC 性能监测线程");
		Thread.currentThread().setName("DC Performance Monitoring Thread");
		
		CommonDao dao = null;
		try {
//			dao = new CommonDao();
			if(Constants.sslServer==null) {
				logger.info("DC监听端口状况（60702）：sslServer=null");
			}else {
				logger.info("DC监听端口状况（60702）：isBind="+Constants.sslServer.isBound());
			}
			
			Future<?> future = Common.getFutureMap().get(Constants.DATA_COLLECT_MANAGER);
			Future<?> futureDetect = Common.getFutureMap().get(Constants.DETECTI_DATA_COLLECT_THREAD_NAME);
			if(future!=null) {
				boolean isDone = future.isDone();
				boolean isCancel = future.isCancelled();
				logger.info("DC已注册数据收集管理线程，isDone="+isDone+",isCancel="+isCancel);
			}else {
				logger.info("DC未注册数据收集管理线程");
			}
			if(futureDetect!=null) {
				logger.info("DC 数据收集管理线程 监测线程 运行中，isDone="+futureDetect.isDone()+",isCancel="+futureDetect.isCancelled());
			}else {
				logger.info("DC 数据收集管理线程 监测线程  未启动");
			}
			long freeMemory = Runtime.getRuntime().freeMemory()/1024/1024;
			long totalMemory = Runtime.getRuntime().totalMemory()/1024/1024;
			long maxMemory = Runtime.getRuntime().maxMemory()/1024/1024;
			long usedMemory = totalMemory - freeMemory;
			int activeCount = Thread.activeCount();//活跃线程数
			logger.debug("内存使用情况：total-> " + totalMemory +" MB, used -> "+ usedMemory +" MB, max -> " + maxMemory+" MB, free -> " + freeMemory+" MB \r\n 活跃线程数： "+ activeCount);
			Common.detecSelf();
			if(logger.isDebugEnabled() && "druid".equalsIgnoreCase(Constants.DB_POOL_TYPE)){

			}
			
			
//			int [] links = getDBLinkSize(dao);
			/* 查询当前DC，数据库连接数 */
//			logger.debug("当前数据库连接数："+links[0]+" 活动连接数："+links[1]);
//			System.gc();
		} catch (Exception e) {
			logger.error("Monitoring their own thread abnormality",e);
		}finally{
			if(dao!=null){
				dao.close();
				dao=null;
			}
			logger.debug("结束");
		}
	}
	
	public static void main (String []args){
		new Thread(new DetecSelfThread()).start();
		/*Map<String, String> map =  System.getenv();
		pl("用户名称"+map.get("USERNAME"));
		pl("计算机名称"+map.get("COMPUTERNAME"));
		pl(""+map.get("USEROOMAIN"));*/
	}
	
	/**
	 * 查询当前DC的数据库连接数
	 * @time Jan 13, 2013-4:25:03 PM
	 * @param dao
	 * @return
	 * @throws Exception
	 */
	public int[] getDBLinkSize(CommonDao dao) throws Exception{
		ArrayList<String> fields = new ArrayList<String>();
		fields.add("dbLinks");
		fields.add("activeLinks");
//		Map<String, String> map =  System.getenv();
		String dbLinkSizeSql = "select count(1) dbLinks,count(decode(status,'ACTIVE',1,0,0)) activeLinks from v$session t where lower(username) =lower(?) and  lower(t.MACHINE) = lower(?)";
		String dbUserName = Constants.DB_USER_NAME;
//		String computerName = map.get("COMPUTERNAME");
		String computerName =  InetAddress.getLocalHost().getHostName();
		logger.debug("计算机名称："+computerName);
//		logger.debug("计算机名称："+name);
		ArrayList<Map<String, String>> data = dao.dbSelect(dbLinkSizeSql, fields,dbUserName,computerName);
		if(data!= null && data.size()>0){
			String val = data.get(0).get("dbLinks");
			String val2 = data.get(0).get("activeLinks");
			return new int[]{val == null ? -1 : Integer.parseInt(val),val2 == null ? -1 : Integer.parseInt(val2)};
		}else{
			return new int[]{-1,-1};
		}
	}
	
	public static void pl(Object obj) {
		System.out.println(obj==null?null:obj.toString());
	}
}