package demo.frame;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Panel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Vector;

import javax.imageio.ImageIO;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.border.EmptyBorder;

import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;

import demo.common.*;
import demo.frame.FaceRecognition.GroupOperateDialog;
import demo.module.*;
import netsdk.callback.SUBSCRIBE_CALLBACK;
import netsdk.lib.CommonFunctions;
import netsdk.lib.DeviceSdk;
import netsdk.lib.ErrorCodeAndConst;
import netsdk.lib.ToolKits;
import netsdk.struct.NET_DVR_IVE_VFD_RESULT_FACE_DATA_INFO_T;
import netsdk.struct.NET_SDK_AVPSTORE_FACE_ABSTRACT_INFO;
import netsdk.struct.NET_SDK_IVE_FACE_MATCH_T;
import netsdk.struct.NET_SDK_TLV_BUFFER_DESC;


class FaceRecognizeFrame extends JFrame{
	private static final long serialVersionUID = 1L;
	
	private Vector<String> chnlist = new Vector<String>(); 
	private boolean isRealplay = false;
	private static boolean isAttach = false;
	// 预览句柄
	public static NativeLong m_hPlayHandle = new NativeLong(0);
	
	// 获取界面窗口
	private static JFrame frame = new JFrame();   
	
	public FaceRecognizeFrame() {
	    setTitle(Res.string().getRealplay());
	    setLayout(new BorderLayout());
	    pack();
	    setSize(800, 560);
	    setResizable(false);
	    setLocationRelativeTo(null);
		LoginModule.init();   // 打开工程，初始化
		
    	try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
        	e.printStackTrace();
        } 
	 
	    loginPanel = new LoginPanel();	    
	    add(loginPanel, BorderLayout.NORTH);
	    
	    facePanel = new FaceRecognitionEventPanel();
	    add(facePanel, BorderLayout.CENTER);

	    //operatePanel = new JPanel();
	    //add(operatePanel, BorderLayout.CENTER);
	    //operatePanel.setLayout(new FlowLayout());
	    
	    
	    //faceDataBaseBtn = new JButton(Res.string().getGroupOperate());
	    //operatePanel.add(faceDataBaseBtn);
	    
//	    Dimension dim = new Dimension();
//		dim.width = 120;
//		dim.height = 20;
//		faceDataBaseBtn.setPreferredSize(dim);
//		faceDataBaseBtn.setEnabled(false);
		
		

	    
	    loginPanel.addLoginBtnActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {	   	    
				if(loginPanel.checkLoginText()) {
					if(login()) {
						frame = ToolKits.getFrame(e);
						frame.setTitle(Res.string().getFaceRecognition() + " : " + Res.string().getOnline());
					}
				}
			}
		});
	    
	    loginPanel.addLogoutBtnActionListener(new ActionListener() {		
			@Override
			public void actionPerformed(ActionEvent e) {
				frame.setTitle(Res.string().getFaceRecognition());
				logout();	
			}
		});
        
	    addWindowListener(new WindowAdapter() {
	    	public void windowClosing(WindowEvent e) {
	    		LoginModule.logout();
	    		LoginModule.cleanup();   // 关闭工程，释放资源
	    		dispose();	
	    		
	    		SwingUtilities.invokeLater(new Runnable() {
	    			public void run() {
	    				FunctionList demo = new FunctionList();
	    				demo.setVisible(true);
	    			}
	    		});
	    	}
	    });
	}
		
	
	// 登录
	public boolean login() {
		if(LoginModule.login(loginPanel.ipTextArea.getText(), 
						Integer.parseInt(loginPanel.portTextArea.getText()), 
						loginPanel.nameTextArea.getText(), 
						new String(loginPanel.passwordTextArea.getPassword()))) {
	
			loginPanel.setButtonEnable(true);
						
			setEnable(true);
			for(int i = 1; i < LoginModule.m_stDeviceInfo.videoInputNum + 1; i++) {
				chnlist.add(Res.string().getChannel() + " " + String.valueOf(i));
				
			}
			// 登陆成功，将通道添加到控件
			chnComboBox.setModel(new DefaultComboBoxModel(chnlist));	
			
		} else {
			JOptionPane.showMessageDialog(null, Res.string().getLoginFailed() + ", " + ToolKits.getErrorCodeShow(), Res.string().getErrorMessage(), JOptionPane.ERROR_MESSAGE);
			return false;
		}
		return true;
	}
	
	// 登出
	public void logout() {

		RealPlayModule.stopRealPlay(m_hPlayHandle);
		LoginModule.logout();

		loginPanel.setButtonEnable(false);
		setEnable(false);
		realplayWindowPanel.repaint();   	
		
		isRealplay = false;
		realplayBtn.setText(Res.string().getStartRealPlay());
				
		isAttach = false;
		
		attachBtn.setText(Res.string().getAttach());
		globalPicLabel.setText(Res.string().getGlobalPicture() + " ------ [" + Res.string().getEventType() + "]");

		globalPicShowPanel.setOpaque(true); 
		globalPicShowPanel.repaint();

		personPicShowPanel.setOpaque(true); 
		personPicShowPanel.repaint();
	
		candidatePicShowPanel.setOpaque(true); 
		candidatePicShowPanel.repaint();

        timeTextField.setText("");
    	sexTextField.setText("");
    	ageTextField.setText("");
    	raceTextField.setText("");
    	eyeTextField.setText("");
    	mouthTextField.setText("");
    	maskTextField.setText("");
    	beardTextField.setText("");   	

    	nameTextField.setText("");
    	sexTextField2.setText("");
    	birthdayTextField.setText("");
    	idNoTextField.setText("");
    	groupIdTextField.setText("");
    	groupNameTextField.setText("");
    	similaryTextField.setText("");
		
		for(int i = 0; i < LoginModule.m_stDeviceInfo.videoInputNum + 1; i++) {
			chnlist.clear();
		}
		
		chnComboBox.setModel(new DefaultComboBoxModel());	
		
//		groupId = 0;	
//		globalBufferedImage = null;
//		personBufferedImage = null;
//		candidateBufferedImage = null;	
		
	}
	private void setEnable(boolean bln) {
		
		chnComboBox.setEnabled(bln);
		realplayBtn.setEnabled(bln);
		attachBtn.setEnabled(bln);
		faceDataBaseBtn.setEnabled(bln);
		faceEventRecordBtn.setEnabled(bln);
	}
	/*
	 * 预览界面通道、码流设置  以及抓图面板
	 */
	private FaceRecognitionEventPanel facePanel;
	
	/*
	 * 登录
	 */
	private LoginPanel loginPanel;	
	// 人脸库界面
	private GroupOperateDialog groupOperateDialog = null;

	private JPanel operatePanel;;   // 通道、预览、订阅		

	
	private JLabel chnlabel;
	private JComboBox chnComboBox;
	private JButton realplayBtn;
	private JButton attachBtn;
    private JButton faceDataBaseBtn;
    private JButton faceEventRecordBtn;
    private Panel realplayWindowPanel;
	private static PaintPanel globalPicShowPanel;
	private static PaintPanel personPicShowPanel;
	private static PaintPanel candidatePicShowPanel;
    
	private static JLabel globalPicLabel;
	
    /*
     * 人脸信息
     */
	private static JTextField timeTextField;
	private static JTextField sexTextField;
	private static JTextField ageTextField;
	private static JTextField raceTextField;
	private static JTextField eyeTextField;
	private static JTextField mouthTextField;
	private static JTextField maskTextField;
	private static JTextField beardTextField;
	
	/*
	 * 候选人信息
	 */
	private static JTextField nameTextField;
	private static JTextField sexTextField2;
	private static JTextField birthdayTextField;
	private static JTextField idNoTextField;
	private static JTextField groupIdTextField;
	private static JTextField groupNameTextField;
	private static JTextField similaryTextField;
	/*
	 * 预览
	 */

    
	public class FaceRecognitionEventPanel extends JPanel{
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		public FaceRecognitionEventPanel() {
			BorderEx.set(this, "", 2);
			setLayout(new BorderLayout());
			
			JPanel operatePanel = new JPanel();   // 通道、预览、订阅		
			JPanel panel = new JPanel();	

			add(operatePanel, BorderLayout.NORTH);
			add(panel, BorderLayout.CENTER);
			
			/*
			 * 操作面板：通道、预览、订阅按钮
			 */
			chnlabel = new JLabel(Res.string().getChannel());
			chnComboBox = new JComboBox(); 
			
			realplayBtn = new JButton(Res.string().getStartRealPlay());
			attachBtn = new JButton(Res.string().getAttach());	
			faceDataBaseBtn = new JButton(Res.string().getGroupOperate());
			faceEventRecordBtn = new JButton("查找事件记录");
			
			operatePanel.setLayout(new FlowLayout());
			operatePanel.add(chnlabel);
			operatePanel.add(chnComboBox);
			operatePanel.add(realplayBtn);
			operatePanel.add(attachBtn);
			operatePanel.add(faceDataBaseBtn);
			operatePanel.add(faceEventRecordBtn);
			
			Dimension dim = new Dimension();
			dim.width = 120;
			dim.height = 20;
			
			chnComboBox.setPreferredSize(new Dimension(80, 20));
			attachBtn.setPreferredSize(dim);
			realplayBtn.setPreferredSize(dim);
			faceDataBaseBtn.setPreferredSize(dim);
			faceEventRecordBtn.setPreferredSize(dim);
			
			chnComboBox.setEnabled(false);
			realplayBtn.setEnabled(false);
			attachBtn.setEnabled(false);
			faceDataBaseBtn.setEnabled(false);
			faceEventRecordBtn.setEnabled(false);
			
			/*
			 * 预览、图片面板
			 */
			JPanel realplayPanel = new JPanel();
			JPanel globalPicPanel = new JPanel();
			JPanel personPicPanel = new JPanel();
			JPanel candidatePanel = new JPanel();
			
			realplayPanel.setBorder(new EmptyBorder(0, 5, 5, 5));
			globalPicPanel.setBorder(new EmptyBorder(0, 5, 5, 5));
			personPicPanel.setBorder(new EmptyBorder(0, 5, 5, 5));
			candidatePanel.setBorder(new EmptyBorder(0, 5, 5, 5));
			
			panel.setLayout(new GridLayout(2, 2));
			
			panel.add(realplayPanel);
			panel.add(globalPicPanel);
			panel.add(personPicPanel);
			panel.add(candidatePanel);
			
			/*
			 * 预览面板
			 */
			JLabel realplayLabel = new JLabel(Res.string().getRealplay());
			realplayWindowPanel = new Panel();
			realplayWindowPanel.setBackground(Color.GRAY);
			realplayPanel.setLayout(new BorderLayout());
			realplayPanel.add(realplayLabel, BorderLayout.NORTH);
			realplayPanel.add(realplayWindowPanel, BorderLayout.CENTER);
	
			/*
			 * 全景图面板
			 */
			globalPicLabel = new JLabel(Res.string().getGlobalPicture() + " ------ [" + Res.string().getEventType() + "]");
			globalPicShowPanel = new PaintPanel();
			globalPicPanel.setLayout(new BorderLayout());
			globalPicPanel.add(globalPicLabel, BorderLayout.NORTH);
			globalPicPanel.add(globalPicShowPanel, BorderLayout.CENTER);
			
			/*
			 * 人脸图面板
			 */
			JLabel personPiclabel = new JLabel(Res.string().getPersonPicture());
			personPicShowPanel = new PaintPanel();
			JPanel faceDataPanel = new JPanel();
			
			Dimension dimension = new Dimension();
			dimension.width = 200;
			faceDataPanel.setPreferredSize(dimension);
			
			personPicPanel.setLayout(new BorderLayout());
			personPicPanel.add(personPiclabel, BorderLayout.NORTH);
			personPicPanel.add(personPicShowPanel, BorderLayout.CENTER);
			personPicPanel.add(faceDataPanel, BorderLayout.EAST);
			
			// 人脸信息
			JLabel timeLabel = new JLabel(Res.string().getTime(), JLabel.CENTER);
			JLabel sexLabel = new JLabel(Res.string().getSex(), JLabel.CENTER);
			JLabel ageLabel = new JLabel(Res.string().getAge(), JLabel.CENTER);
			JLabel raceLabel = new JLabel(Res.string().getRace(), JLabel.CENTER);
			JLabel eyeLabel = new JLabel(Res.string().getEye(), JLabel.CENTER);
			JLabel mouthLabel = new JLabel(Res.string().getMouth(), JLabel.CENTER);
			JLabel maskLabel = new JLabel(Res.string().getMask(), JLabel.CENTER);
			JLabel beardLabel = new JLabel(Res.string().getBeard(), JLabel.CENTER);
			
			Dimension dimension1 = new Dimension();
			dimension1.height = 18;
			dimension1.width = 50;
			timeLabel.setPreferredSize(dimension1);
			sexLabel.setPreferredSize(dimension1);
			ageLabel.setPreferredSize(dimension1);
			raceLabel.setPreferredSize(dimension1);
			eyeLabel.setPreferredSize(dimension1);
			mouthLabel.setPreferredSize(dimension1);
			maskLabel.setPreferredSize(dimension1);
			beardLabel.setPreferredSize(dimension1);
			
			timeTextField = new JTextField();
			sexTextField = new JTextField();
			ageTextField = new JTextField();
			raceTextField = new JTextField();
			eyeTextField = new JTextField();
			mouthTextField = new JTextField();
			maskTextField = new JTextField();
			beardTextField = new JTextField();
			
			Dimension dimension2 = new Dimension();
			dimension2.width = 125;
			dimension2.height = 19;
			timeTextField.setPreferredSize(dimension2);
			sexTextField.setPreferredSize(dimension2);
			ageTextField.setPreferredSize(dimension2);
			eyeTextField.setPreferredSize(dimension2);
			raceTextField.setPreferredSize(dimension2);
			mouthTextField.setPreferredSize(dimension2);
			maskTextField.setPreferredSize(dimension2);
			beardTextField.setPreferredSize(dimension2);
			
			timeTextField.setHorizontalAlignment(JTextField.CENTER);
			sexTextField.setHorizontalAlignment(JTextField.CENTER);
			ageTextField.setHorizontalAlignment(JTextField.CENTER);
			eyeTextField.setHorizontalAlignment(JTextField.CENTER);
			raceTextField.setHorizontalAlignment(JTextField.CENTER);
			mouthTextField.setHorizontalAlignment(JTextField.CENTER);
			maskTextField.setHorizontalAlignment(JTextField.CENTER);
			beardTextField.setHorizontalAlignment(JTextField.CENTER);
			
			timeTextField.setEnabled(false);
			sexTextField.setEnabled(false);
			ageTextField.setEnabled(false);
			eyeTextField.setEnabled(false);
			raceTextField.setEnabled(false);
			mouthTextField.setEnabled(false);
			maskTextField.setEnabled(false);
			beardTextField.setEnabled(false);
			
			timeTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			sexTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			ageTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			eyeTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			raceTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			mouthTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			maskTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			beardTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			
			faceDataPanel.setLayout(new FlowLayout());
			
			faceDataPanel.add(timeLabel);
			faceDataPanel.add(timeTextField);
			faceDataPanel.add(sexLabel);
			faceDataPanel.add(sexTextField);
			faceDataPanel.add(ageLabel);
			faceDataPanel.add(ageTextField);
			faceDataPanel.add(raceLabel);
			faceDataPanel.add(raceTextField);
			faceDataPanel.add(eyeLabel);
			faceDataPanel.add(eyeTextField);
			faceDataPanel.add(mouthLabel);
			faceDataPanel.add(mouthTextField);
			faceDataPanel.add(maskLabel);
			faceDataPanel.add(maskTextField);
			faceDataPanel.add(beardLabel);
			faceDataPanel.add(beardTextField);

			/*
			 * 候选人图面板
			 */
			JLabel candidateLabel = new JLabel(Res.string().getCandidatePicture());
			candidatePicShowPanel = new PaintPanel();
			JPanel candidateDataPanel = new JPanel();
			
			Dimension dimension4 = new Dimension();
			dimension4.width = 220;
			candidateDataPanel.setPreferredSize(dimension4);
			
			candidatePanel.setLayout(new BorderLayout());
			candidatePanel.add(candidateLabel, BorderLayout.NORTH);
			candidatePanel.add(candidatePicShowPanel, BorderLayout.CENTER);
			candidatePanel.add(candidateDataPanel, BorderLayout.EAST);

			// 候选人信息
			JLabel nameLabel = new JLabel(Res.string().getName(), JLabel.CENTER);
			JLabel sexLabel2 = new JLabel(Res.string().getSex(), JLabel.CENTER);
			JLabel birthdayLabel = new JLabel(Res.string().getBirthday(), JLabel.CENTER);
			JLabel idNoLabel = new JLabel(Res.string().getIdNo(), JLabel.CENTER);
			JLabel groupIdLabel = new JLabel(Res.string().getFaceGroupId(), JLabel.CENTER);
			JLabel groupNameLabel = new JLabel(Res.string().getFaceGroupName(), JLabel.CENTER);
			JLabel similaryLabel = new JLabel(Res.string().getSimilarity(), JLabel.CENTER);
			
			Dimension dimension3 = new Dimension();
			dimension3.height = 19;
			dimension3.width = 80;
			nameLabel.setPreferredSize(dimension3);
			sexLabel2.setPreferredSize(dimension3);
			birthdayLabel.setPreferredSize(dimension3);
			idNoLabel.setPreferredSize(dimension3);
			groupIdLabel.setPreferredSize(dimension3);
			groupNameLabel.setPreferredSize(dimension3);
			similaryLabel.setPreferredSize(dimension3);
			
			nameTextField = new JTextField();
			sexTextField2 = new JTextField();
			birthdayTextField = new JTextField();
			idNoTextField = new JTextField();
			groupIdTextField = new JTextField();
			groupNameTextField = new JTextField();
			similaryTextField = new JTextField();
	
			nameTextField.setHorizontalAlignment(JTextField.CENTER);
			sexTextField2.setHorizontalAlignment(JTextField.CENTER);
			birthdayTextField.setHorizontalAlignment(JTextField.CENTER);
			idNoTextField.setHorizontalAlignment(JTextField.CENTER);
			groupIdTextField.setHorizontalAlignment(JTextField.CENTER);
			groupNameTextField.setHorizontalAlignment(JTextField.CENTER);
			similaryTextField.setHorizontalAlignment(JTextField.CENTER);
			
			nameTextField.setPreferredSize(dimension2);
			sexTextField2.setPreferredSize(dimension2);
			birthdayTextField.setPreferredSize(dimension2);
			idNoTextField.setPreferredSize(dimension2);
			groupIdTextField.setPreferredSize(dimension2);
			groupNameTextField.setPreferredSize(dimension2);
			similaryTextField.setPreferredSize(dimension2);
			
			nameTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			sexTextField2.setFont(new Font("黑体", Font.PLAIN, 11));
			birthdayTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			idNoTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			groupIdTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			groupNameTextField.setFont(new Font("黑体", Font.PLAIN, 11));
			similaryTextField.setFont(new Font("黑体", Font.PLAIN, 11));			
			
			nameTextField.setEnabled(false);
			sexTextField2.setEnabled(false);
			birthdayTextField.setEnabled(false);
			idNoTextField.setEnabled(false);
			groupIdTextField.setEnabled(false);
			groupNameTextField.setEnabled(false);
			similaryTextField.setEnabled(false);
			
			candidateDataPanel.setLayout(new FlowLayout());
			
			candidateDataPanel.add(nameLabel);
			candidateDataPanel.add(nameTextField);
			candidateDataPanel.add(sexLabel2);
			candidateDataPanel.add(sexTextField2);
			candidateDataPanel.add(birthdayLabel);
			candidateDataPanel.add(birthdayTextField);
			candidateDataPanel.add(idNoLabel);
			candidateDataPanel.add(idNoTextField);
			candidateDataPanel.add(groupIdLabel);
			candidateDataPanel.add(groupIdTextField);
			candidateDataPanel.add(groupNameLabel);	
			candidateDataPanel.add(groupNameTextField);	
			candidateDataPanel.add(similaryLabel);	
			candidateDataPanel.add(similaryTextField);	
			
			// 预览
			realplayBtn.addActionListener(new ActionListener() {				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					realplay();
				}
			});		
			
			// 订阅
			attachBtn.addActionListener(new ActionListener() {				
				@Override
				public void actionPerformed(ActionEvent arg0) {
					realLoadPicture();
				}
			});
			
			// 人脸库操作
			faceDataBaseBtn.addActionListener(new ActionListener() {			
				@Override
				public void actionPerformed(ActionEvent arg0) {
					groupOperateDialog = new GroupOperateDialog();
					groupOperateDialog.setVisible(true);	
				}
			});
			
			
			// 查询人脸识别事件记录
			faceEventRecordBtn.addActionListener(new ActionListener() {			
				@Override
				public void actionPerformed(ActionEvent arg0) {
//					FindFaceEventRecordDialog faceEventRecordDialog = new FindFaceEventRecordDialog();
//					faceEventRecordDialog.setVisible(true);	
				}
			});
		}
		
		// 预览
		public void realplay() {
			if(!isRealplay) {
				m_hPlayHandle = RealPlayModule.startRealPlay(chnComboBox.getSelectedIndex(), 
					    		0,
					    		realplayWindowPanel);
				if(m_hPlayHandle.longValue() > 0) {
					realplayWindowPanel.repaint();
					isRealplay = true;
					chnComboBox.setEnabled(false);
					realplayBtn.setText(Res.string().getStopRealPlay());
					
					//FaceRecognitionModule.renderPrivateData(m_hPlayHandle, 1);
				} else {
					JOptionPane.showMessageDialog(null, ToolKits.getErrorCodeShow(), Res.string().getErrorMessage(), JOptionPane.ERROR_MESSAGE);
				}
			} else {
				//FaceRecognitionModule.renderPrivateData(m_hPlayHandle, 0);
				
				RealPlayModule.stopRealPlay(m_hPlayHandle);
				realplayWindowPanel.repaint();
				isRealplay = false;
				chnComboBox.setEnabled(true);
				realplayBtn.setText(Res.string().getStartRealPlay());	
			}	
		}
		// 订阅
		public void realLoadPicture() {
			if(!isAttach) {
				if(LoginModule.m_stDeviceInfo.deviceType == ErrorCodeAndConst.NET_SDK_NVR) {
					
					boolean ret =  LoginModule.netsdk.NET_SDK_SetSubscribCallBack(AnalyzerDataCB.getInstance(), null);
			        if(!ret) {
			        	System.err.println("NET_SDK_SetSubscribCallBack Failed, Error:" + ToolKits.getErrorCodePrint());
			        } else {
			        	System.out.println("订阅成功！");
			        }
				}
				//boolean ret = FaceRecognitionModule.Subscrib(chnComboBox.getSelectedIndex(), AnalyzerDataCB.getInstance());
//				if(m_hAttachHandle.longValue() != 0) {
//					isAttach = true;			
//					attachBtn.setText(Res.string().getDetach());
//				} else {
//					JOptionPane.showMessageDialog(null, ToolKits.getErrorCodeShow(), Res.string().getErrorMessage(), JOptionPane.ERROR_MESSAGE);
//				}
			} else {
				//FaceRecognitionModule.stopRealLoadPicture(m_hAttachHandle);
				isAttach = false;
				attachBtn.setText(Res.string().getAttach());

				globalPicLabel.setText(Res.string().getGlobalPicture() + " ------ [" + Res.string().getEventType() + "]");	

				globalPicShowPanel.setOpaque(true); 
				globalPicShowPanel.repaint();

				personPicShowPanel.setOpaque(true); 
				personPicShowPanel.repaint();
			
				candidatePicShowPanel.setOpaque(true); 
				candidatePicShowPanel.repaint();

		        timeTextField.setText("");
		    	sexTextField.setText("");
		    	ageTextField.setText("");
		    	raceTextField.setText("");
		    	eyeTextField.setText("");
		    	mouthTextField.setText("");
		    	maskTextField.setText("");
		    	beardTextField.setText("");   	

		    	nameTextField.setText("");
		    	sexTextField2.setText("");
		    	birthdayTextField.setText("");
		    	idNoTextField.setText("");
		    	groupIdTextField.setText("");
		    	groupNameTextField.setText("");
		    	similaryTextField.setText("");
		    	
//		    	groupId = 0;
//				globalBufferedImage = null;
//				personBufferedImage = null;
//				candidateBufferedImage = null;	
			}
		}
		
	}
	
	/**
	 * 写成静态主要是防止被回收
	 */
	private static class AnalyzerDataCB implements SUBSCRIBE_CALLBACK {  	
		private AnalyzerDataCB() {}
			
		private static class AnalyzerDataCBHolder {
			private static final AnalyzerDataCB instance = new AnalyzerDataCB();
		}
		
		public static AnalyzerDataCB getInstance() {
			return AnalyzerDataCBHolder.instance;
		}

		public void invoke(NativeLong lUserID, int dwCommand, Pointer pBuf, int dwBufLen, Pointer pUser) 
        {
            if (dwBufLen == 0 || pBuf == null) {
                return;
            }   
            int offSetLen = 0;
			int len = 0;
			int restLen = dwBufLen;
			switch(dwCommand)
            {
//			|	NET_SDK_IVE_FACE_MATCH_T	|
//			-------------------------
//			|	图片数据(抓拍)	|
//			-------------------------
//			|	NET_SDK_AVPSTORE_FACE_ABSTRACT_INFO		|
//			-------------------------
//			|	NET_DVR_IVE_VFD_RESULT_FACE_DATA_INFO_T		|
//			-------------------------
//			|	图片数据(人脸目标)	|
//			-------------------------
//			|	NET_SDK_TLV_BUFFER_DESC		|
//			-------------------------
//			|	图片数据(背景)	|
				case ErrorCodeAndConst.NET_SDK_N9000_ALARM_TYPE_FACE_MATCH:  ///< 人脸识别事件
				{	
					
					NET_SDK_IVE_FACE_MATCH_T msg = new NET_SDK_IVE_FACE_MATCH_T();
					len = msg.size();
					// 耗时20ms左右
            		
            		if(restLen < len)
                    {
                        break;
                    } 
            		ToolKits.GetPointerData(pBuf, msg);  
            		
            		offSetLen += len;//地址偏移
        			restLen -= len;//剩余长度
        			
            		if(restLen < msg.imgLen)
            			break;
            		byte[] data = pBuf.getByteArray(offSetLen, msg.imgLen);//抓拍图片
            		
            		ByteArrayInputStream byteArr = new ByteArrayInputStream(data);
	            	try {
	            		BufferedImage bImage = ImageIO.read(byteArr);
						
	            		personPicShowPanel.setImage(bImage);
	            		personPicShowPanel.setOpaque(false); 
	            		personPicShowPanel.repaint();
						
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            	offSetLen += msg.imgLen;//地址偏移
        			restLen -= msg.imgLen;//剩余长度
	            	     
        			NET_SDK_AVPSTORE_FACE_ABSTRACT_INFO nsafai = new NET_SDK_AVPSTORE_FACE_ABSTRACT_INFO();
        			len = nsafai.size();
        			if(restLen < len)
                    {
                        break;
                    } 
        			CommonFunctions.GetPointerDataToStruct(pBuf, offSetLen, nsafai);
        			offSetLen += len;//地址偏移
        			restLen -= len;//剩余长度
        			
        			NET_DVR_IVE_VFD_RESULT_FACE_DATA_INFO_T ndivrfdit = new NET_DVR_IVE_VFD_RESULT_FACE_DATA_INFO_T();
        			len = ndivrfdit.size();
        			if(restLen < len)
                    {
                        break;
                    } 
        			CommonFunctions.GetPointerDataToStruct(pBuf, offSetLen, ndivrfdit);
        			offSetLen += len;//地址偏移
        			restLen -= len;//剩余长度
        			
        			if(restLen < ndivrfdit.stFaceImgData.dataLen)
            			break;
        			data = pBuf.getByteArray(offSetLen, ndivrfdit.stFaceImgData.dataLen);//目标图片
        			byteArr = new ByteArrayInputStream(data);
	            	try {
	            		BufferedImage bImage = ImageIO.read(byteArr);
						
	            		candidatePicShowPanel.setImage(bImage);
	            		candidatePicShowPanel.setOpaque(false); 
	            		candidatePicShowPanel.repaint();
						
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
        			offSetLen += ndivrfdit.stFaceImgData.dataLen;//地址偏移
        			restLen -= ndivrfdit.stFaceImgData.dataLen;//剩余长度
        			
        			NET_SDK_TLV_BUFFER_DESC nstbd = new NET_SDK_TLV_BUFFER_DESC();
        			len = nstbd.size();
        			if(restLen < len)
                    {
                        break;
                    } 
        			CommonFunctions.GetPointerDataToStruct(pBuf, offSetLen, nstbd);
        			offSetLen += len;//地址偏移
        			restLen -= len;//剩余长度
        			
        			if(restLen < nstbd.dwSize)
                    {
                        break;
                    } 
        			data = pBuf.getByteArray(offSetLen, nstbd.dwSize);//目标图片
        			
        			byteArr = new ByteArrayInputStream(data);
	            	try {
	            		BufferedImage bImage = ImageIO.read(byteArr);
						
	            		globalPicShowPanel.setImage(bImage);
	            		globalPicShowPanel.setOpaque(false); 
	            		globalPicShowPanel.repaint();
						
					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
	            	
     	            // 释放内存
     	            msg = null;
	     	        nsafai = null;
	     	        ndivrfdit = null;
	     	        nstbd = null;
     	            System.gc();
                      
					break;
				} 

				default:
					break;
            }
                   
//			return 0;           
        }
	
		/**
		 * 保存人脸识别事件图片
		 * @param pBuffer 抓拍图片信息
		 * @param dwBufSize 抓拍图片大小
		 * @param faceRecognitionInfo 人脸识别事件信息
		 */
//		public void saveFaceRecognitionPic(Pointer pBuffer, int dwBufSize, 
//								           DEV_EVENT_FACERECOGNITION_INFO faceRecognitionInfo) throws FileNotFoundException {
//          	index = -1;
//			globalBufferedImage = null;
//			personBufferedImage = null;
//			candidateBufferedImage = null;	
//			
//			File path = new File("./FaceRecognition/");
//            if (!path.exists()) {
//                path.mkdir();
//            }
//
//            if (pBuffer == null || dwBufSize <= 0) {
//            	return;
//            }
//
//			/////////////// 保存全景图 ///////////////////
//            if(faceRecognitionInfo.bGlobalScenePic == 1) {
//            	
//    			String strGlobalPicPathName = path + "\\" + faceRecognitionInfo.UTC.toStringTitle() + "_FaceRecognition_Global.jpg"; 
//    	    	byte[] bufferGlobal = pBuffer.getByteArray(faceRecognitionInfo.stuGlobalScenePicInfo.dwOffSet, 
//    	    											   faceRecognitionInfo.stuGlobalScenePicInfo.dwFileLenth);
//    			ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(bufferGlobal);
//    			
//    			try {
//    				globalBufferedImage = ImageIO.read(byteArrInputGlobal);
//    				if(globalBufferedImage != null) {
//    					File globalFile = new File(strGlobalPicPathName);
//						if(globalFile != null) {
//							ImageIO.write(globalBufferedImage, "jpg", globalFile);
//						}
//    				}				
//    			} catch (IOException e2) {
//    				e2.printStackTrace();
//    			}
//            }
//
//            /////////////// 保存人脸图 /////////////////////////
//            if(faceRecognitionInfo.stuObject.stPicInfo != null) {
//            	String strPersonPicPathName = path + "\\" + faceRecognitionInfo.UTC.toStringTitle() + "_FaceRecognition_Person.jpg"; 
//    	    	byte[] bufferPerson = pBuffer.getByteArray(faceRecognitionInfo.stuObject.stPicInfo.dwOffSet, 
//    	    											   faceRecognitionInfo.stuObject.stPicInfo.dwFileLenth);
//    			ByteArrayInputStream byteArrInputPerson = new ByteArrayInputStream(bufferPerson);
//    			
//    			try {
//    				personBufferedImage = ImageIO.read(byteArrInputPerson);
//    				if(personBufferedImage != null) {
//    					File personFile = new File(strPersonPicPathName);
//						if(personFile != null) {
//							ImageIO.write(personBufferedImage, "jpg", personFile);
//						}
//    				}		
//    			} catch (IOException e2) {
//    				e2.printStackTrace();
//    			}
//            }
//            
//            ///////////// 保存对比图 //////////////////////         	
//            if(faceRecognitionInfo.nRetCandidatesExNum > 0 
//            		&& faceRecognitionInfo.stuCandidatesEx != null) {
//            	int maxValue = -1;
//            	
//            	// 设备可能返回多张图片，这里只显示相似度最高的
//            	int[] nSimilary = new int[faceRecognitionInfo.nRetCandidatesExNum];
//            	for(int i = 0; i < faceRecognitionInfo.nRetCandidatesExNum; i++) {
//            		nSimilary[i] = faceRecognitionInfo.stuCandidatesEx[i].bySimilarity & 0xff;
//            	}
//            	
//  
//        		for(int i = 0; i < nSimilary.length; i++) {
//        			if(maxValue < nSimilary[i]) {
//        				maxValue = nSimilary[i];
//        				index = i;
//        			} 
//        		}           	
//            	
//            	String strCandidatePicPathName = path + "\\" + faceRecognitionInfo.UTC.toStringTitle() + "_FaceRecognition_Candidate.jpg";     
//            	
//            	// 每个候选人的图片个数：faceRecognitionInfo.stuCandidatesEx[index].stPersonInfo.wFacePicNum，
//            	// 正常情况下只有1张。如果有多张，此demo只显示第一张
//	    		byte[] bufferCandidate = pBuffer.getByteArray(faceRecognitionInfo.stuCandidatesEx[index].stPersonInfo.szFacePicInfo[0].dwOffSet, 
//	    													  faceRecognitionInfo.stuCandidatesEx[index].stPersonInfo.szFacePicInfo[0].dwFileLenth);
//				ByteArrayInputStream byteArrInputCandidate = new ByteArrayInputStream(bufferCandidate);
//				
//				try {
//					candidateBufferedImage = ImageIO.read(byteArrInputCandidate);
//					if(candidateBufferedImage != null) {
//						File candidateFile = new File(strCandidatePicPathName);
//						if(candidateFile != null) {
//							ImageIO.write(candidateBufferedImage, "jpg", candidateFile);
//						}
//					}				
//				} catch (IOException e2) {
//					e2.printStackTrace();
//				}		
//            	   	
//            }
//		}
//		
		/**
		 * 保存人脸检测事件图片
		 * @param pBuffer 抓拍图片信息
		 * @param dwBufSize 抓拍图片大小
		 * @param faceDetectInfo 人脸检测事件信息
		 */
//		public void saveFaceDetectPic(Pointer pBuffer, int dwBufSize, 
//									  DEV_EVENT_FACEDETECT_INFO faceDetectInfo) throws FileNotFoundException {		
//			File path = new File("./FaceDetection/");
//	        if (!path.exists()) {
//	            path.mkdir();
//	        }
//
//	        if (pBuffer == null || dwBufSize <= 0) {
//	        	return;
//	        }	   
//	        
//	        // 小图的 stuObject.nRelativeID 来匹配大图的 stuObject.nObjectID，来判断是不是 一起的图片
//	        if(groupId != faceDetectInfo.stuObject.nRelativeID) {   ///->保存全景图 
//	        	personBufferedImage = null;
//	        	groupId = faceDetectInfo.stuObject.nObjectID;
//	        				
//				String strGlobalPicPathName = path + "\\" + faceDetectInfo.UTC.toStringTitle() + "_FaceDetection_Global.jpg"; 
//		    	byte[] bufferGlobal = pBuffer.getByteArray(0, dwBufSize);
//				ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(bufferGlobal);
//				
//				try {
//					globalBufferedImage = ImageIO.read(byteArrInputGlobal);
//					if(globalBufferedImage != null) {
//						File globalFile = new File(strGlobalPicPathName);
//						if(globalFile != null) {
//							ImageIO.write(globalBufferedImage, "jpg", globalFile);
//						}
//					}				
//				} catch (IOException e2) {
//					e2.printStackTrace();
//				}
//	        } else if(groupId == faceDetectInfo.stuObject.nRelativeID){   ///->保存人脸图
//		        if(faceDetectInfo.stuObject.stPicInfo != null) {
//		        	String strPersonPicPathName = path + "\\" + faceDetectInfo.UTC.toStringTitle() + "_FaceDetection_Person.jpg"; 
//			    	byte[] bufferPerson = pBuffer.getByteArray(0, dwBufSize);
//					ByteArrayInputStream byteArrInputPerson = new ByteArrayInputStream(bufferPerson);
//					
//					try {
//						personBufferedImage = ImageIO.read(byteArrInputPerson);
//						if(personBufferedImage != null) {						
//							File personFile = new File(strPersonPicPathName);
//							if(personFile != null) {
//								ImageIO.write(personBufferedImage, "jpg", personFile);
//							}	
//						}			
//					} catch (IOException e2) {
//						e2.printStackTrace();
//					}
//		        }
//	        }
//		}
	}
	

}

public class FaceRecognize {
	//private static JButton btnNewButton;

	public static void main(String[] args) {	
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				FaceRecognizeFrame demo = new FaceRecognizeFrame();	
				demo.setTitle("人脸识别");
				
				demo.setVisible(true);
			}
		});		
	}
}
