

package demo.frame;


import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;


import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;

import demo.module.LoginModule;
import netsdk.lib.CommonFunctions;
import netsdk.lib.DeviceSdk;
import netsdk.struct.NET_SDK_IVE_FACE_MATCH_ADD_ALBUM_INFO;
import netsdk.struct.NET_SDK_IVE_FACE_MATCH_QUERY_ALBUM_REPLY_INFO;

import javax.swing.JTextArea;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.awt.GridLayout;
import java.awt.Image;

import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.Component;
import javax.swing.border.LineBorder;
import java.awt.Color;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;


public class AddModifyTarget extends JDialog{
	private boolean add;//是添加还是修改目标


	private int serverId;
	private DefaultTableModel model;

	private JButton btnOK;
	private JLabel lblName;
	private JTextField txtName;
	private JButton btnCancel;
	private int selectedRow;
	private JPanel picPanel;
	private JLabel lblPic;
	private JTextField txtAge;
	private JTextField txtTel;
	private JComboBox comboBoxSex;
	private JTextField txtCertificatenum;
	private JTextField txtRemark;
	
	private String libName;
	private byte gender;
	private String country;
	private String province;
	private String city;
	private byte idType;
	private String idNum;
	private byte priority;
	private String discription;
	private short birthYear;
	private byte birthMonth;
	private byte birthDay;
	private NET_SDK_IVE_FACE_MATCH_QUERY_ALBUM_REPLY_INFO fa;

	private String picPath = "";
	private JComboBox comboBoxType;

	public AddModifyTarget() {
		setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		setType(Type.UTILITY);
		setModal(true);
		setResizable(false);
		setTitle("Add Target");
		setSize(427,314);
//
		setLocationRelativeTo(null);//居中显示	
		getContentPane().setLayout(null);
								
		lblName = new JLabel("Name:");
		lblName.setBounds(196, 43, 31, 14);
		getContentPane().add(lblName);
		
		txtName = new JTextField();
		txtName.setBounds(263, 40, 100, 20);
		getContentPane().add(txtName);
		txtName.setText("Name");
		txtName.setColumns(10);
		
		btnOK = new JButton("OK");
		btnOK.setBounds(112, 231, 65, 23);
		getContentPane().add(btnOK);
		
		btnCancel = new JButton("Cancel");
		btnCancel.setBounds(196, 231, 82, 23);
		getContentPane().add(btnCancel);
		
		JLabel lblNewLabel = new JLabel("Age:");
		lblNewLabel.setBounds(196, 103, 46, 14);
		getContentPane().add(lblNewLabel);
		
		picPanel = new JPanel();
		picPanel.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent arg0) {
				JFileChooser jfc;//图片选择
				jfc = new JFileChooser();
        		jfc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        		jfc.setFileFilter(new javax.swing.filechooser.FileFilter() {
        			@Override			
        			public boolean accept(File file) {							
        				if ((file.isFile() && (file.getName().contains(".jpg")||file.getName().contains(".png") ))) {					
        					return true;				
        				} 
        				else {					
        					return false;				
        					} 			
        				}
        			public String getDescription() {
        		        return "图片(*.jpg|*.png)";
        			}
        		});
                jfc.showDialog(new JLabel(), "选择图片");  
                File file = jfc.getSelectedFile();                
                  			  				
				try {							  									  
					  ImageIcon i1 = new ImageIcon(file.getAbsolutePath());
					  i1.getImage().flush();					 
					  i1.setImage(i1.getImage().getScaledInstance(lblPic.getWidth(),lblPic.getHeight(),Image.SCALE_DEFAULT));					  
					  lblPic.setIcon(i1);	
					  picPath = file.getAbsolutePath();
				} 
				catch (Exception e) {
					e.printStackTrace();
				}						  		
                //pbPanel.backUpPathTxt.setText(file.getAbsolutePath());
                
			}
		});
		picPanel.setBorder(new LineBorder(new Color(0, 0, 0)));
		picPanel.setBounds(10, 10, 150, 137);
		getContentPane().add(picPanel);
		picPanel.setLayout(null);
		
		lblPic = new JLabel("              +");
		lblPic.setBounds(0, 0, 150, 137);
		picPanel.add(lblPic);
		
		
		// 格式 
		String DefaultFormat = "yyyy-MM-dd"; 
		// 开始时间 
		Date date_start = new Date(); 
		// 字体
		Dimension dimension = new Dimension(130, 24);
						
		comboBoxSex = new JComboBox();
		comboBoxSex.setModel(new DefaultComboBoxModel(new String[] {"male", "female"}));
		comboBoxSex.setBounds(263, 70, 100, 20);
		getContentPane().add(comboBoxSex);
		
		JLabel lblNewLabel_2 = new JLabel("Gender:");
		lblNewLabel_2.setBounds(196, 73, 46, 14);
		getContentPane().add(lblNewLabel_2);
		
		txtAge = new JTextField();
		txtAge.setBounds(263, 100, 100, 20);
		getContentPane().add(txtAge);
		txtAge.setColumns(10);
		
		JLabel lblProvince = new JLabel("Tel:");
		lblProvince.setBounds(196, 133, 57, 14);
		getContentPane().add(lblProvince);
		
		txtTel = new JTextField();
		txtTel.setBounds(263, 130, 100, 20);
		getContentPane().add(txtTel);
		txtTel.setColumns(10);
		
		JLabel lblCertificatenum = new JLabel("IDNum:");
		lblCertificatenum.setBounds(196, 161, 57, 14);
		getContentPane().add(lblCertificatenum);
		
		txtCertificatenum = new JTextField();
		txtCertificatenum.setText("CertificateNum");
		txtCertificatenum.setBounds(263, 158, 100, 20);
		getContentPane().add(txtCertificatenum);
		txtCertificatenum.setColumns(10);
		
		JLabel lblRemark = new JLabel("Remark:");
		lblRemark.setBounds(92, 191, 46, 14);
		getContentPane().add(lblRemark);
		
		txtRemark = new JTextField();
		txtRemark.setText("Remark");
		txtRemark.setBounds(161, 188, 206, 20);
		getContentPane().add(txtRemark);
		txtRemark.setColumns(10);
		
		comboBoxType = new JComboBox();
		comboBoxType.setModel(new DefaultComboBoxModel(new String[] {"Vistor", "Allow List", "Block List"}));
		comboBoxType.setBounds(263, 10, 100, 20);
		getContentPane().add(comboBoxType);
		
		JLabel lblNewLabel_1 = new JLabel("ListType:");
		lblNewLabel_1.setBounds(196, 10, 54, 15);
		getContentPane().add(lblNewLabel_1);
		
		btnCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				//SetBirthday(null);
				dispose();
			}
		});
		DefaultTableCellRenderer dCellRenderer = new DefaultTableCellRenderer();
		dCellRenderer.setHorizontalAlignment(JLabel.CENTER);

		
		
		btnOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if(add) {
					AddOrModifyTarget(1);
					dispose();
					//JOptionPane.showMessageDialog(null, "add", "", JOptionPane.WARNING_MESSAGE);	
				}
				else {
					//AddOrModifyTarget(ErrorCodeAndConst.FACE_MATCH_SET_TARGET);
					dispose();
//					FaceMatch_TargetInfo targetInfo = ft;						
//					targetInfo.targetProperty.priority = 1;
//						
//					FaceMatch_TargetProperty ftp = new FaceMatch_TargetProperty();
//					
//					String bir = birthdayPicker.getInnerTextField().getText();						
//					ftp.birthYear = Short.parseShort(bir.substring(0, 4));
//					ftp.birthMonth = Byte.parseByte(bir.substring(5, 7));
//					ftp.birthDay = Byte.parseByte(bir.substring(8, 10));
//					
//					String tempName = txtName.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.name, 0, tempName.getBytes().length);
//					tempName = txtCountry.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.country, 0, tempName.getBytes().length);	
//					tempName = txtProvince.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.province, 0, tempName.getBytes().length);
//					tempName = txtCity.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.city, 0, tempName.getBytes().length);
//					tempName = txtRemark.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.discription, 0, tempName.getBytes().length);
//					tempName = txtCertificatenum.getText().trim();
//					System.arraycopy(tempName.getBytes(), 0, ftp.id, 0, tempName.getBytes().length);
//									
//					ftp.gender = (byte)comboBoxSex.getSelectedIndex();		
//					ftp.idType = (byte)comboBoxCertiType.getSelectedIndex();						
//					ftp.priority = (byte)comboBoxPriority.getSelectedIndex();
//					
//					targetInfo.targetProperty = ftp;
//					
//					
//					FaceMatch_TargetImageData ftid = new FaceMatch_TargetImageData();																													
//					byte[] fileByte = null;
//					try {		
//						if(picPath.length() > 0) {
//							 BufferedImage bufferedImage = ImageIO.read(new File(picPath));
//					            ftid.width = bufferedImage.getWidth();
//					            ftid.height = bufferedImage.getHeight();
//					            File file = new File(picPath);
//					            fileByte = Files.readAllBytes(file.toPath());
//					            ftid.dataLen = fileByte.length;
//					            ftid.type = 0;	
//						}
//			           			            							            
//			
//			        } catch (IOException e) {
//			            e.printStackTrace();
//			        }			
//					Pointer pImageData = new Memory(fileByte.length);
//					pImageData.write(0, fileByte, 0, fileByte.length);
//					ftid.data = pImageData;
//					
//					targetInfo.imageData = ftid;
//					
//					int pLen = targetInfo.size();		
//					Pointer pNativeData = new Memory(pLen);
//					CommonFunctions.SetStructDataToPointer(targetInfo, pNativeData, 0);	//结构体加入指针内存	
//					//System.out.println(targetInfo.size());	
//					boolean ret = LoginModule.netsdk.Plat_FaceMatchOperateEx(LoginModule.loginId, ErrorCodeAndConst.FACE_MATCH_SET_TARGET, 
//							pNativeData, pLen, null, 0, null);
//					
//					// 释放内存
//					long peer1 = Pointer.nativeValue(pImageData);
//					Native.free(peer1);// 手动释放内存
//					Pointer.nativeValue(pImageData, 0);
//					
//					// 释放内存
//					long peer = Pointer.nativeValue(pNativeData);
//					Native.free(peer);// 手动释放内存
//					Pointer.nativeValue(pNativeData, 0);
//					
//					
//					if(ret) {
//						dispose();
//					}												
						//JOptionPane.showMessageDialog(null, "请输入合法的名称", "", JOptionPane.WARNING_MESSAGE);	
					//JOptionPane.showMessageDialog(null, "modify", "", JOptionPane.WARNING_MESSAGE);	
				}
						
				
				
			}
		});
	}
	private boolean VerifyData() {
		libName = txtName.getText();
		if(libName.length() > 0) {
			
		}
		else {
			return false;
		}		
		
		gender = (byte)comboBoxSex.getSelectedIndex();
		country = txtAge.getText();
		if(country.length() > 0) {
			
		}
		else {
			
		}
			
		return true;
	}
	public void SetDialogName(String name) {
		setTitle(name);
		add = name.contains("Add");
	}

	private void SetName(String name) {
		txtName.setText(name);		
	}

	private void SetSex(int gender) {
		comboBoxSex.setSelectedIndex(gender);
	}
	private void SetAge(int Age) {
		txtAge.setText(String.valueOf(Age));
	}
	private void SetTel(byte[] tel) {
		String temp = "";
		temp = CommonFunctions.ByteToStr(tel,"UTF8");
		txtTel.setText(temp);
	}

	private void SetCertificateId(byte[] id) {
		String temp = "";
		temp = CommonFunctions.ByteToStr(id,"UTF8");
		txtCertificatenum.setText(temp);
	}

//	private void SetRemark(FaceMatch_TargetProperty _ft) {
//		String temp = "";
//		temp = CommonFunctions.ByteToStr(_ft.discription,"UTF8");
//		txtRemark.setText(temp);
//	}
	
//	public void SetTargetInfo(FaceMatch_TargetInfo _ft) {
//		ft = _ft;
//		SetAlbum(ft.albumInfo);
//		UpdateData(ft);//显示所有参数信息
//	}
	public void SetData() {
		
	}
	public void SetPic(String _picPath) {
		try {	
			picPath = _picPath;
			  ImageIcon i1 = new ImageIcon(picPath);
			  i1.getImage().flush();					 
			  i1.setImage(i1.getImage().getScaledInstance(lblPic.getWidth(),lblPic.getHeight(),Image.SCALE_DEFAULT));					  
			  lblPic.setIcon(i1);	
			  
		} 
		catch (Exception e) {
			e.printStackTrace();
		}		
	}
	private void UpdateData(NET_SDK_IVE_FACE_MATCH_QUERY_ALBUM_REPLY_INFO _ft) {
		String temp = "";
		temp = CommonFunctions.ByteToStr(_ft.stBaseInfo.szName,"UTF8");
		SetName(temp);

		SetSex(_ft.stBaseInfo.iMale);
		SetAge(_ft.stBaseInfo.iAge);
		SetTel(_ft.stBaseInfo.szTel);
//		SetCity(_ft.targetProperty);
//		SetCertiType(_ft.targetProperty.idType);
		SetCertificateId(_ft.stBaseInfo.szIdentifyNum);
//		SetPriority(_ft.targetProperty.priority);
//		SetRemark(_ft.stBaseInfo.);
	}
	private void AddOrModifyTarget(int command) {	
		String szUrl = "AddTargetFace";
		String tempXML = "<?xml version = '1.0' encoding='utf-8'?>" +
                                        "<config version='1.7' xmlns='http://www.ipc.com/ver10' >" +
                                        "<types>" +
                                        "<listType> " +
                                          "<enum>strangerList</enum>" + 
                                          "<enum>whiteList</enum>" +  
                                          "<enum>blackList</enum>" + 
                                        "</listType>" +  
                                        "<sexType>" + 
                                          "<enum>male</enum>" +  
                                          "<enum>female</enum>" + 
                                        "</sexType>" +  
                                        "<formatType>" + 
                                          "<enum>jpg</enum>" +                                         
                                        "</formatType>" + 
                                        "</types>" +
                                        "<personInfo>" +
                                        "<listType type='listType'>%s</listType>" + //目标类型，白名单或者黑名单
                                        "<name type='string' maxLen='127'><![CDATA[%s]]></name>" +  //此处名称为UTF8格式字符串
                                        "<sex type='sexType'>%s</sex>" +
                                        "<age type='uint32'>%d</age>" +
                                        "<identifyNumber type='string' maxLen='127'><![CDATA[%s]]></identifyNumber>" +
                                        "<telephone type='string' maxLen='63'><![CDATA[%s]]></telephone>" +  
                                        "<comment type='string' maxLen='63'><![CDATA[%s]]></comment>" + 
                                        "</personInfo>" +
                                        "<faceImgs type='list' maxCount='5' count='%d'>" +  //图片张数
                                        "<item>" +
                                        "<pictureData><![CDATA[%s]]></pictureData>" +  //图片数据，Base64String
                                        "<pictureNum>%d</pictureNum>" +
                                        "<Width>%d</Width>" +
                                        "<Height>%d</Height>" +  
                                        "<Height>%d</Height>" +
                                        "<format>%s</format>" +  //图片格式，"jpg"
                                        "<size>%d</size>" +
                                        "</item>" +
                                        "</faceImgs>" +
                                    "</config>";		
		
		byte[] nameArr = null;
		try {
			nameArr = txtName.getText().trim().getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String name = new String(nameArr);
		
		String listType = "whiteList";
		switch(comboBoxType.getSelectedIndex()) {
			case 0:
				listType = "strangerList";
				break;
			case 1:
				listType = "whiteList";
				break;
			case 2:
				listType = "blackList";
				break;
		}
				
		String sex = comboBoxSex.getSelectedIndex() == 0?"male":"female";		
		int age = Integer.parseInt(txtAge.getText().trim());
		String telephone = txtTel.getText().trim();
		
		String identifyNumber = txtCertificatenum.getText().trim();
		
		String remark = txtRemark.getText().trim();
		int count = 1;
		String pictureData = CommonFunctions.getImageStr(picPath);
		int pictureNum = 1;
		ImageIcon imageIcon = new ImageIcon(picPath); 
		int Width = imageIcon.getIconWidth(); 
		int Height = imageIcon.getIconHeight();
		String format = "jpg";
		int size = CommonFunctions.pathSize(picPath);
		String sendXml = String.format(tempXML, listType,name,sex,age,identifyNumber,telephone,remark,count,
				pictureData,pictureNum,Height,Width,Width,format,size);
		System.out.println(sendXml);
		IntByReference lpBytesReturned = new IntByReference();
		Pointer pNativeData = new Memory(1024 * 1024); 	       		
        boolean ret = DeviceSdk.INSTANCE.NET_SDK_TransparentConfig(LoginModule.m_hLoginHandle, 
        		sendXml, szUrl, pNativeData, 1024 * 1024, lpBytesReturned);
        if (ret)
        {
        	byte[] data = pNativeData.getByteArray(0, lpBytesReturned.getValue());
        	String temp = CommonFunctions.ByteToStr(data,"UTF8");          	
			System.out.println(temp);								
        }
        CommonFunctions.FreePointer(pNativeData);//释放内存
				
	}
	public void SetTarget(NET_SDK_IVE_FACE_MATCH_QUERY_ALBUM_REPLY_INFO _fa) {
		fa = _fa;
		UpdateData(fa);//显示所有参数信息
	}
}
