package com.nms.server;

import java.sql.Connection;

import javax.swing.JOptionPane;

import org.apache.log4j.Logger;

import com.fang.lang.Db;
import com.nms.server.common.Common;
import com.nms.server.common.Config;
import com.nms.server.common.Constants;
import com.nms.server.thread.InitServerThread;
import com.nms.server.thread.WritePidThread;
import com.nms.server.thread.netty.NettyServer;
import com.nms.server.thread.socket.SSLServerManager;
import com.nms.server.util.DbPool;


/**
 *  DataController 程序启动主方法类
 *  @date Aug 10, 2011 1:55:25 PM
 *	@author ZhangGang
 *
 */
public class DataController {
	private static Logger logger = Logger.getLogger(DataController.class);
	
	public static void doShutDownWork() {
		logger.info("注册程序退出事件");
		Runtime.getRuntime().addShutdownHook(new Thread() {
				public void run() {
					try {
//						Thread.currentThread().setName("退出DC，缓存数据清理线程");
						Thread.currentThread().setName("Exit DC, Caching Data Cleaning Thread");
						Common.stop();//程序停止运行
						logger.info("停止DataController，处理缓存数据。。。");
						Common.clearDataInMem();						
						logger.info("停止DataController，处理缓存数据 完成");
					} catch (Exception ex) {
						logger.error("Stop DataController, cache data entry anomalies, cache data to disk", ex);//1.全部入库，入库异常时存盘 或 2.全部存盘，下次启动时入库
						Common.saveDataInMemToDisk();			
						logger.error("Stop DataController, cache data entry anomalies, cache data stored in hard disk to complete", ex);//1.全部入库，入库异常时存盘 或 2.全部存盘，下次启动时入库
					}
				}
		});
	} 
	/**
	 * DataController程序启动入口
	 * @time Jan 5, 2012-11:37:59 AM
	 * @param args
	 */
	public static void main(String [] args) {
//		Thread.currentThread().setName("主程序");
		Thread.currentThread().setName("Main Program");
		logger.info("------- DataController 启动开始------------");
		
		doShutDownWork();//注册shutdown事件
		
		//书写PID
		Common.service.submit(new WritePidThread());
//		WritePidThread pidth = new WritePidThread();
//		pidth.run();
		
		//- 初始化数据库连接池（在优化方向：将数据库连接池创建及维护通过 其专有维护线程实现独立管理）
		try {
			Thread.sleep(3000);
			DbPool.initPool();
			//初始化Common.Db
			Common.initDb(new Db(new Db.DataSource() {
				@Override
				public Connection getConnection() {
					try {
						return DbPool.getConnection();
					} catch (Exception e) {
						logger.error("",e);
					}
					return null;
				}
			}));
			Thread.sleep(3000);
			String sequenceTable=Config.getString("sequence.table", "detection_info");
			if(!sequenceTable.equals("0")){
				String[] split=sequenceTable.split(",");
				Common.initSequence(Common.getDb().getConnection(),split);
			}
			
		} catch (ClassNotFoundException e) {
			logger.error("Load database driver failure");
		} catch (Exception e) {
			logger.error("Initialization of connection pool exception："+e.getMessage());
		}
		
		//- 启动加密通讯端口监听
		try {
			Common.service.submit(new SSLServerManager(Constants.SSL_SERVER_PORT,true));		//与web和Agent端通讯线程启动
			if(Constants.NETTY_SERVER_FLAG == 1){
				//启动netty server
				Common.service.submit(new NettyServer(Constants.NETTY_SERVER_PORT, Constants.NETTY_SERVER_SSL));
			}
		} catch (Exception e) {
//			String info = "通讯服务启动失败！\n请确定程序是否未启动或检查服务端口["+Constants.SSL_SERVER_PORT+"]未被占用！\n"+e.getMessage();
			String info = "The communication service failed to start! \n please confirm whether the program has not started or checked the service port["+Constants.SSL_SERVER_PORT+"]is not occupied!！\n"+e.getMessage();
//			String info = "i18n_server.DataController.showMsg_n81i["+Constants.SSL_SERVER_PORT+"]i18n_server.DataController.isExists_n81i！\n"+e.getMessage();
			logger.error(info);//i18nlog
//			JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
//			JOptionPane.showMessageDialog(null, info, "Error", JOptionPane.ERROR_MESSAGE);
			JOptionPane.showMessageDialog(null, info, "Error", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}
		
		//- 获取本机IP
		/*try {
			String localIp = Common.getLocalIp();
			
			if(StringUtils.isBlank(localIp)){
				String info = "读取本地IP失败 程序无法启动 请检查配置文件";
				logger.error(info);
				JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
				System.exit(0);
			}
		} catch (Exception e) {
			String info = "主线程执行异常，被迫中止\n"+e.getMessage();
			logger.error(info);
			JOptionPane.showMessageDialog(null, info, "错误", JOptionPane.ERROR_MESSAGE);
			System.exit(0);
		}*/

		//- 执行加载启动操作
		Common.service.submit(new InitServerThread());
	}
}
