package com.gx.obe.management;

import java.io.File;

import org.eclipse.core.runtime.Platform;
import org.eclipse.equinox.app.IApplication;
import org.eclipse.equinox.app.IApplicationContext;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.PlatformUI;

import com.gx.obe.CertificateValidationDialog;
import com.gx.obe.OnStartInit;
import com.gx.obe.application.AppApplication;
import com.gx.obe.application.HttpStatusMonitorStateProces;
import com.gx.obe.application.SysetmStatus;
import com.gx.obe.common.file.enumeration.FileConstants;
import com.gx.obe.components.core.Constants;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.util.utils.FileUtils;
import com.gx.obe.web.service.UserLoginRecordService;
import com.gx.security.CertificateException;
import com.gx.tools.ca.CACert;
import com.gx.tools.ftp.ApacheFtpServer;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

import common.Logger;

/**
 * This class controls all aspects of the application's execution
 */
public class ManagementApplication implements IApplication {
	private Logger LOG = Logger.getLogger(ManagementApplication.class);
	private ApacheFtpServer apacheFtpServer;
	public static CACert EXPERT_CERT;
	
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#start(org.eclipse.equinox.app.IApplicationContext)
	 */
	public Object start(IApplicationContext context) {
		Display display = PlatformUI.createDisplay();
		try {
			OnStartInit.initSystemConfig(Constants.TERMINAL_MANAGEMENT );
			OnStartInit.initPluginId(Activator.PLUGIN_ID);
			if(valLicense()){
				OnStartInit.installDriver();
//				zipUpdateFile();
//				startFtpServer();
				// 关闭进度条
				Platform.endSplash();
				
				SysetmStatus.USER_LOGINS_TATUS = false; 
				HttpStatusMonitorStateProces.addHttpStatusMonitor();
				LoginDialog loginDialog = new LoginDialog();
				loginDialog.open();
				int loginType = loginDialog.getLoginType();
				if(loginType == IApplication.EXIT_OK){
					return  AppApplication.EXIT_TYPE;
				}else if(loginType == IApplication.EXIT_RESTART){
					return IApplication.EXIT_RESTART;
				}
				// 第一次登录后如果发现没有设置产品版本类型，则默认设置为正式版本
				if(PropertiesUtils.getProperty(ConfigConstants.PRODUCT_TYPE, "").length() == 0) {
					PropertiesUtils.saveProperty(ConfigConstants.PRODUCT_TYPE, ConfigConstants.PRODUCT_TYPE_FINAL);
				}
				MainDialog mainDialog = new MainDialog();
				mainDialog.open();
				 return AppApplication.EXIT_TYPE;
			}
//			int returnCode = PlatformUI.createAndRunWorkbench(display, new ApplicationWorkbenchAdvisor());
//			if (returnCode == PlatformUI.RETURN_RESTART) {
//				return IApplication.EXIT_RESTART;
//			}
			return IApplication.EXIT_OK;
		} catch(Exception e){
			LOG.error("评标管理打开失败！", e);
			return IApplication.EXIT_OK;
		}finally {
			disposite();
			display.dispose();
		}
	}
	
	public static void exit(){
		AppApplication.exit();
	}
	public static void restart(){
		AppApplication.restart();
	}
	/* (non-Javadoc)
	 * @see org.eclipse.equinox.app.IApplication#stop()
	 */
	public void stop() {
		if (!PlatformUI.isWorkbenchRunning())
			return;
		final IWorkbench workbench = PlatformUI.getWorkbench();
		final Display display = workbench.getDisplay();
		display.syncExec(new Runnable() {
			public void run() {
				if (!display.isDisposed())
					workbench.close();
			}
		});
	}
	
	/**
	 * @Description: 验证license
	 * @author guoyr
	 * @return
	 */
	private boolean valLicense(){
		boolean valLicenseSuccess = false;
		File certificteFile = null;
		com.gx.security.CertValidator certValidator = null;
		try {
			certValidator = com.gx.security.CertValidator.getInstance();
			certificteFile = new File(FileConstants.PRODUCT_ROOT.concat(certValidator.getSequence()).concat(".cer"));
			certValidator.setPubKeyPath(FileConstants.LICENSE_PUBKEY_PATH);
			certValidator.setCertPath(certificteFile.getAbsolutePath());
			valLicenseSuccess = certValidator.validateAuthorization(Constants.PRODUCE_EN_NAME, Constants.PRODUCE_VERSION);
			if(!valLicenseSuccess) {
				File productCertFile = new File(FileConstants.PRODUCT_ROOT.concat("00-00-00-00-00-00").concat(".cer"));
				if(productCertFile.exists()){
					FileUtils.copy(productCertFile.getAbsolutePath(), certificteFile.getAbsolutePath());
					certValidator.reloadCert();
					valLicenseSuccess = certValidator.validateAuthorization(Constants.PRODUCE_EN_NAME, Constants.PRODUCE_VERSION);
				}
			}
			
		} catch (CertificateException e) {
			valLicenseSuccess = false;
		}finally{
			if(!valLicenseSuccess){
				
				CertificateValidationDialog licenseValidationDialog = new CertificateValidationDialog(new Shell());
				licenseValidationDialog.setShellOnTop();
				// 关闭闪屏
				Platform.endSplash();
				licenseValidationDialog.open();		
				// 如果在license导入界面中验证失败，或取消了license验证，则认为验证系统，需要退出系统
				valLicenseSuccess = licenseValidationDialog.valAuthorization();
			}
		}
	
		return valLicenseSuccess;
	}
	
	/**
	 * @Description:释放资源 
	 * @author guoyr
	 */
	private void disposite(){
		if (null != Constants.USER && null != Constants.USER.getUserAccount()) {
			UserLoginRecordService loginRecordService = new UserLoginRecordService();
			loginRecordService.logout(Constants.USER.getUserAccount(), Constants.TERMINAL_MANAGEMENT, Constants.USER.getLoginRecordId(), Constants.USER.getId());
		}
		if(null != apacheFtpServer){
			apacheFtpServer.stop();
		}
		// 释放系统资源
		ResourceManager.dispose();
		SWTResourceManager.dispose();
		
//		// 关闭socket服务器
//		if(null != serverSocket && !serverSocket.isClosed()){
//			try {
//				serverSocket.close();
//			} catch (IOException e) {
//			}
//		}
//		// 关闭摄像头和视频流
//		if(null != senderVideo){
//			senderVideo.closeSender();
//		}
	}

}
