package com.gx.obe.management.shell;

import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketException;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.core.ImageResolver;
import org.eclipse.swt.core.widgets.ESepator;
import org.eclipse.swt.core.widgets.ImageButton;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;

import com.gx.obe.ColorConstants;
import com.gx.obe.business.entity.TorrentFile;
import com.gx.obe.business.http.HttpUtils;
import com.gx.obe.common.icons.IconsActivator;
import com.gx.obe.common.widget.utils.MenuFunctionUtils;
import com.gx.obe.config.ConfigConstants;
import com.gx.obe.config.utils.PropertiesUtils;
import com.gx.obe.management.Lisener.SelectNetWorkListener;
import com.gx.obe.util.utils.LogUtils;
import com.gx.obe.util.utils.NetWorkUtils;
import com.gx.obe.web.entity.TransactionServer;
import com.gx.obe.web.entity.auth.AuthLoginRecordEntity;
import com.gx.obe.web.entity.auth.Menu;
import com.gx.obe.web.entity.tender.TenderProjectEntity;
import com.gx.obe.web.service.TorrentFileService;
import com.gx.obe.web.service.UserLoginRecordService;
import com.gx.security.SystemTool;
import com.swtdesigner.ResourceManager;
import com.swtdesigner.SWTResourceManager;

/**
 * @Description: 
 * @author guoyr
 */
public class ChooseNetWorkToDownLoadShell extends Shell {

	private Composite composite;
	private ImageResolver imageResolver = new ImageResolver();
	private TenderProjectEntity tenderProjectEntity;
	private FTPClient ftp = new FTPClient();
	private static String DEAFULT_REMOTE_CHARSET="GBK";
	private static int DEAFULT_REMOTE_PORT=21;// 默认端口
	private Logger LOG = Logger.getLogger(ChooseNetWorkToDownLoadShell.class);
	private String torrentFile  = "torrentFile";
	private MenuFunctionUtils menuFunctionUtils = new MenuFunctionUtils();
	private Menu menu;
	{
		LogUtils.logClass(ChooseNetWorkToDownLoadShell.class);
	}
	
	/**
	 * Create the shell.
	 * @param display
	 */
	public ChooseNetWorkToDownLoadShell(Shell shell,Menu menu, TenderProjectEntity tenderProjectEntity, final SelectNetWorkListener selectNetWorkListener) {
		super(shell, SWT.NO_TRIM |SWT.TOP);
		this.menu = menu;
		setBackground(ColorConstants.SKIN_BG);
		setBackgroundMode(SWT.INHERIT_FORCE);
		FillLayout fillLayout = new FillLayout(SWT.HORIZONTAL);
		fillLayout.marginHeight = 1;
		fillLayout.marginWidth = 1;
		setLayout(fillLayout);
		this.setAlpha(230);
		this.tenderProjectEntity = tenderProjectEntity;
		composite = new Composite(this, SWT.NONE);
		composite.setBackground(ColorConstants.LIGHT_BACKGROUND_COLOR);
		composite.setBackgroundImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/fill_bg.png"));
		composite.setBackgroundMode(SWT.INHERIT_FORCE);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.marginHeight = 0;
		gl_composite.marginWidth = 0;
		gl_composite.verticalSpacing = 0;
		gl_composite.horizontalSpacing = 0;
		composite.setLayout(gl_composite);
		
		final CLabel LANDownLoad = createItem(1);
		LANDownLoad.setText(" 局域网FTP下载");
		LANDownLoad.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				if(LANDownLoad.getEnabled()){
					getShell().close();
					selectNetWorkListener.selectLAN();
				}
			}
		});
		menuFunctionUtils.addFunction(LANDownLoad, "FTP_DOWNLOAD");		
		
		ESepator label_1 = new ESepator(composite, SWT.NONE);
		label_1.setBackground(SWTResourceManager.getColor(227, 233, 238));
		label_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		menuFunctionUtils.addFunction(label_1, "FTP_DOWNLOAD");		
		
		
		final CLabel torrentFileItem = createItem(3);
		torrentFileItem.setText(" 局域网BT下载");
		torrentFileItem.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				if(torrentFileItem.getEnabled()){
					selectNetWorkListener.selectTorrent((TorrentFile)torrentFileItem.getData(torrentFile));
					getShell().close();
				}
				
			}
		});
		menuFunctionUtils.addFunction(torrentFileItem, "BT_DOWNLOAD");		
		
		ESepator label_2 = new ESepator(composite, SWT.NONE);
		label_2.setBackground(SWTResourceManager.getColor(227, 233, 238));
		label_2.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		menuFunctionUtils.addFunction(label_2, "BT_DOWNLOAD");		
		
		final CLabel itemLabel = createItem(2);
		itemLabel.setText(" 网络下载");
		itemLabel.addMouseListener(new MouseAdapter() {
			public void mouseUp(MouseEvent e) {
				if(itemLabel.getEnabled()){
					getShell().close();
					selectNetWorkListener.selectOnline();
				}
			}
		});
		
		menuFunctionUtils.addFunction(itemLabel, "HTTP_DOWNLOAD");		
		
		addListener(SWT.Deactivate, new Listener(){
			public void handleEvent(Event arg0) {
				close();
			}
		});
		menuFunctionUtils.initFunctionAuthority(menu);
		createContents();
		
	}
	
	/**
	 * @Description: 获取项目所属交易系统url
	 * @author guoyr
	 * @return 
	 */
	private String getProjectServerURL(){
		if(null != tenderProjectEntity.getTransactionServerId() && !"".equals(tenderProjectEntity.getTransactionServerId())){
			TransactionServer transactionServer = HttpUtils.getTransactionServer(tenderProjectEntity.getTransactionServerId());
			if(null != transactionServer && null != transactionServer.getServerAddress()){
				return transactionServer.getServerAddress();
			}
		}
		return  "";
	}
	/**
	 * @Description: 创建按钮
	 * @author guoyr
	 * @param URL
	 * @return 
	 */
	private CLabel createItem(int flag){
		
		final ImageButton itemLabel = new ImageButton(composite, SWT.LEFT);
		itemLabel.setBackground(ColorConstants.LIGHT_BACKGROUND_COLOR);
		itemLabel.setLeftMargin(5);
		itemLabel.setRightMargin(5);
		itemLabel.setTopMargin(5);
		itemLabel.setBottomMargin(5);
		itemLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1, 1));
		
		itemLabel.setSurroundMargin(3);
		itemLabel.setActiveSurroundColor(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		itemLabel.setActiveBgColor(ColorConstants.SKIN_BG);
		itemLabel.setActiveForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		itemLabel.setFont(SWTResourceManager.getFont("微软雅黑", 10, SWT.NORMAL));
		itemLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/lan.png"));
		if(flag == 2){
			itemLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/wifi.png"));
			itemLabel.setEnabled(false);
			new Thread(new Runnable(){
				public void run(){
					final boolean connect = NetWorkUtils.isConnNet(getProjectServerURL());
					if(connect){
						Display.getDefault().syncExec(new Runnable(){
							public void run(){
								if(!itemLabel.isDisposed()){
									itemLabel.setEnabled(true);
								}
							}
						});
					}
				}
			}).start();
		}else if(flag == 1){
			itemLabel.setEnabled(false);
			new Thread(new Runnable(){
				public void run(){
					final boolean connect = connection();
					if(connect){
						Display.getDefault().syncExec(new Runnable(){
							public void run(){
								if(!itemLabel.isDisposed()){
									itemLabel.setEnabled(true);
								}
							}
						});
					}
				}
			}).start();
		}else if(flag == 3){
			TorrentFileService torrentFileService = new TorrentFileService();
			TorrentFile torrentFile = torrentFileService.getTorrentFileByTenderId(tenderProjectEntity.getId());
			
			if(null != torrentFile && null != torrentFile.getTenderId() && null != torrentFile.getFileBite()){
				itemLabel.setEnabled(true);
				itemLabel.setData("torrentFile", torrentFile);
			}else{
				itemLabel.setEnabled(false);
			}
		}
		return itemLabel;
	}

	private boolean connection(){
		int port = 21;
		String hostname = PropertiesUtils.getProperty(ConfigConstants.FTP_IP, "");
		try {
			port = Integer.parseInt(PropertiesUtils.getProperty(ConfigConstants.FTP_PORT, "21"));
		} catch (NumberFormatException e) {
		}
		
		if(null == hostname || hostname.length() == 0){
			UserLoginRecordService service = new UserLoginRecordService();
			AuthLoginRecordEntity authLoginRecordEntity = service.getLoginRecordByTenderId(tenderProjectEntity.getId());
			if(null != authLoginRecordEntity && null != authLoginRecordEntity.getIp() && authLoginRecordEntity.getIp().trim().length() > 0){
				hostname = authLoginRecordEntity.getIp();
			}
		}
		
		if(null == hostname || hostname.length() == 0){
			LOG.error("未设置FTP服务器IP");
			return false;
		}
		
		String username = "anonymous";
		String password = null;
		username = PropertiesUtils.getProperty(ConfigConstants.FTP_USERNAME, username);
		password = PropertiesUtils.getProperty(ConfigConstants.FTP_PASSWORD, null);
		if(hostname.equals(SystemTool.getIp())){
			return false;
		}
		return connectionFTP(hostname, username, password, port);
		
	}
	
	
	
	private boolean connectionFTP(String hostname, String username, String password, int port){
		boolean connection = false;
		try {
			//登录FTP服务器
			try {
				//设置超时时间  
				ftp.setDataTimeout(7200);
				//设置默认编码
				ftp.setControlEncoding(DEAFULT_REMOTE_CHARSET);
				//设置默认端口
				ftp.setDefaultPort(DEAFULT_REMOTE_PORT);
				//设置是否显示隐藏文件
				ftp.setListHiddenFiles(false);
				//连接ftp服务器
				if(port > 0){
					ftp.connect(hostname, port);
				}else{
					ftp.connect(hostname);
				}
				connection = true;
			} catch(ConnectException e) {
				LOG.error("FTP服务器连接失败："+ftp.getReplyString()+ftp.getReplyCode(), e);
			} catch (SocketException e) {
				LOG.error("FTP服务器连接失败："+ftp.getReplyString()+ftp.getReplyCode(), e);
			} catch (IOException e) {
				LOG.error("FTP服务器连接失败："+ftp.getReplyString()+ftp.getReplyCode(), e);
			}
			
			// 连接成功后登录FTP服务器
			if(connection){	
				//得到连接的返回编码
				int reply=ftp.getReplyCode();
				if(!FTPReply.isPositiveCompletion(reply)){
					ftp.disconnect();
				}
				//登录失败权限验证失败
				if(!ftp.login(username, password)) {
					ftp.quit();
					ftp.disconnect();
					LOG.error("连接FTP服务器用户或者密码失败："+ftp.getReplyString());
					connection = false;
				}
				if(LOG.isDebugEnabled()){
					LOG.info("成功登录FTP服务器："+hostname+" 端口："+port);
				}
				ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
				// 设置被动模式
				ftp.enterLocalPassiveMode();
				// 设置以二进制方式传输
				ftp.setFileType(FTP.BINARY_FILE_TYPE);
			}else {
				connection = false;
			}
		}catch(IOException e){
			connection = false;
			LOG.error("登录FTP服务器失败："+hostname+" 端口："+port);
		} finally {
			if (ftp.isConnected()) {
				try {
					ftp.disconnect();
				} catch (IOException e) {
				}
			}
		}
		return connection;
	}
	/**
	 * @Description: 鼠标移动至菜单上的监听
	 * @author guoyr
	 * @param composite
	 * @param actionLabel
	 */
	class ActionMouseTrackListener extends MouseTrackAdapter{
		private CLabel actionLabel;
		public ActionMouseTrackListener(CLabel actionLabel){
			this.actionLabel = actionLabel;
		}
		public void mouseEnter(MouseEvent e) {
			actionLabel.setBackground(ColorConstants.SKIN_BG);
			actionLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/point_green.png"));
			actionLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_WHITE));
		}
		public void mouseExit(MouseEvent e) {
			actionLabel.setBackground(ColorConstants.LIGHT_BACKGROUND_COLOR);
			actionLabel.setForeground(null);
			actionLabel.setImage(ResourceManager.getPluginImage(IconsActivator.PLUGIN_ID, "icons/point.png"));
		}
	}
	
	/**
	 * Create contents of the shell.
	 */
	protected void createContents() {
		setSize(197, 128);
		this.setMinimumSize(100, 20);
		this.pack();

	}

	public void close() {
		imageResolver.disposite();
		super.close();
	}
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

}
