package unitTest;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;

import javax.swing.ImageIcon;

import org.junit.Test;

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

import demo.module.LoginModule;
import netsdk.callback.ACCEPT_REGISTER_CALLBACK;
import netsdk.callback.EXCEPTION_CALLBACK;
import netsdk.callback.LIVE_DATA_CALLBACK;
import netsdk.callback.SUBSCRIBE_CALLBACK;
import netsdk.callback.impl.ACCEPT_REGISTER_CALLBACK_IMPL;
import netsdk.callback.impl.SUBSCRIBE_CALLBACK_IMPL;
import netsdk.lib.CommonFunctions;
import netsdk.lib.DeviceSdk;
import netsdk.lib.ErrorCodeAndConst;
import netsdk.struct.LPNET_SDK_CLIENTINFO;
import netsdk.struct.LPNET_SDK_DEVICEINFO;
import netsdk.struct.NET_DVR_SUBSCRIBE_REPLY;
import netsdk.struct.NET_SDK_DEV_SUPPORT;
import netsdk.struct.REG_LOGIN_INFO;
import netsdk.struct.LPNET_SDK_DEVICEINFO.ByReference;
import unitTest.NET_SDK_A2IPC_Test.devIntelist;
import unitTest.NET_SDK_A2IPC_Test.intelist;
public class Register {

	public static ACCEPT_REGISTER_CALLBACK arc = null;
	public static EXCEPTION_CALLBACK eci = null;
	public static NativeLong loginId;
	public static boolean m_SubscribFaceMatch;//是否订阅人脸报警
	public static boolean m_SubscribFaceDetect;//是否订阅人脸检测
	public static String m_serverAddressVFD;//
	public static SUBSCRIBE_CALLBACK FaceAlarmCB;
	public static LPNET_SDK_DEVICEINFO.ByReference lpDeviceInfo;
	public Register() {
		// TODO Auto-generated constructor stub
	}
	@Test
	public void A() {
		Boolean initResult = CommonFunctions.init();
		//DeviceSdk.INSTANCE.NET_SDK_SetConnectTime(200,1);
		if(!initResult)
			return;
		else {
				
			eci = new EXCEPTION_CALLBACK_IMPL();
			System.out.println("start exception listening...");
	        DeviceSdk.INSTANCE.NET_SDK_SetSDKMessageCallBack(0, null, eci, null);
			boolean ret = DeviceSdk.INSTANCE.NET_SDK_SetLogToFile(true,"D:\\A文档",false,4);	
			 // TODO 设置NVR主动注册上报回调
			REG_LOGIN_INFO[] rli = new REG_LOGIN_INFO[3];
			rli[0] = new REG_LOGIN_INFO();
			rli[1] = new REG_LOGIN_INFO();
			rli[2] = new REG_LOGIN_INFO();
			rli[0].deviceId = 1;	
			rli[1].deviceId = 33;
			rli[2].deviceId = 2011;
			
			
			
			try {
	            System.arraycopy("admin".getBytes("UTF-8"), 0, rli[0].m_szUserName, 0, "admin".getBytes("UTF-8").length);
	            System.arraycopy("x".getBytes("UTF-8"), 0, rli[0].m_szPasswd, 0, "x".getBytes("UTF-8").length);
	            
	            System.arraycopy("admin".getBytes("UTF-8"), 0, rli[1].m_szUserName, 0, "admin".getBytes("UTF-8").length);
	            System.arraycopy("11".getBytes("UTF-8"), 0, rli[1].m_szPasswd, 0, "11".getBytes("UTF-8").length);
	            
	            System.arraycopy("admin".getBytes("UTF-8"), 0, rli[2].m_szUserName, 0, "admin".getBytes("UTF-8").length);
	            System.arraycopy("123456".getBytes("UTF-8"), 0, rli[2].m_szPasswd, 0, "123456".getBytes("UTF-8").length);
	            
	        } catch (UnsupportedEncodingException e) {
	            e.printStackTrace();
	        }
			
			Memory lpInBuffer = new Memory(3 * rli[0].size());
			CommonFunctions.SetStructArrToPointerData(rli, lpInBuffer);
			System.out.println("NET_SDK_AddRegisterDeviceInfo...");						
			DeviceSdk.INSTANCE.NET_SDK_AddRegisterDeviceInfo(lpInBuffer,3);
			long peer = Pointer.nativeValue(lpInBuffer);
			Native.free(peer);// 手动释放内存
			Pointer.nativeValue(lpInBuffer, 0);
			
			
			DeviceSdk.INSTANCE.NET_SDK_SetRegisterPort(6715,null,0);
			arc = new _ACCEPT_REGISTER_CALLBACK_IMPL();
			System.out.println("start to listening...");
	        DeviceSdk.INSTANCE.NET_SDK_SetRegisterCallback(arc, null);
			
//
//			lpDeviceInfo = new LPNET_SDK_DEVICEINFO.ByReference();			
//			try {
//				loginId = CommonFunctions.login(lpDeviceInfo);
//			} catch (Throwable e1) {
//				// TODO Auto-generated catch block
//				e1.printStackTrace();
//			}
//			System.out.println("设备id是：" + lpDeviceInfo.deviceID);
			 Scanner s = new Scanner(System.in);
		     while (s.hasNext()){
		         if(s.next().equals("q")){
		             break;
		         }
		     }   
		     try {
				//D();
				//F();
		    	 G();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	}
	public class _ACCEPT_REGISTER_CALLBACK_IMPL implements ACCEPT_REGISTER_CALLBACK {
		@Override
		public void invoke(NativeLong lUserID, NativeLong lRegisterID, ByReference pDeviceInfo, Pointer pUser) {
			loginId = lUserID;
			lpDeviceInfo = pDeviceInfo;
			System.out.println("device connected:" + lRegisterID);
			try {
				String name = new String(pDeviceInfo.deviceName, "GB2312");
				System.out.println("设备名称是：" + name);
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
	}
	public class EXCEPTION_CALLBACK_IMPL implements EXCEPTION_CALLBACK {
		@Override
		public void invoke(int dwType, NativeLong lUserID, NativeLong lHandle, Pointer pUser) {
			
			System.out.println("设备：" + lUserID.intValue() + "状态变化：" + dwType);
		}
	}
	/**
	 * 添加A2 IPC目标信息
	 * @Title: D
	 *
	 * */
	//@Test
	public void D()  throws Throwable{
		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>" +                                       
                                        "</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 = "1".getBytes("UTF-8");
		String listType = "whiteList";
		String name = new String(nameArr);
		//String name = "333";
		String sex = "female";
		int age = 18;
		String identifyNumber = "1";
		String telephone = "1";
		int count = 1;
		String pictureData = CommonFunctions.getImageStr("C:\\Users\\8590\\Desktop\\3.jpg");
		//String pictureData ="";
		int pictureNum = 1;
		ImageIcon imageIcon = new ImageIcon("C:\\Users\\8590\\Desktop\\3.jpg"); 
		int Width = imageIcon.getIconWidth(); 
		int Height = imageIcon.getIconHeight();
		String format = "jpg";
		int size = CommonFunctions.pathSize("C:\\Users\\8590\\Desktop\\3.jpg");

		String sendXml = String.format(tempXML, listType,name,sex,age,identifyNumber,telephone,count,
				pictureData,pictureNum,Width,Height,Height,format,size);
		System.out.println(sendXml);
		//String sendXml = targetInfo.replaceFirst("<sex type=\"sexType\">male</sex>", "<sex type=\"sexType\">female</sex>");
		IntByReference lpBytesReturned = new IntByReference();
		Pointer pNativeData = new Memory(1024 * 1024); 	       
		//boolean ret = DeviceSdk.INSTANCE.NET_SDK_TransparentConfig(loginId, tempXML, szUrl, pNativeData, 1024 * 1024, lpBytesReturned);
        
        boolean ret = DeviceSdk.INSTANCE.NET_SDK_TransparentConfig(loginId, 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);								
        }
     // 释放内存
		long peer = Pointer.nativeValue(pNativeData);
		Native.free(peer);// 手动释放内存
		Pointer.nativeValue(pNativeData, 0);				
//		File saveFile = new File("D:\\1.jpg");
//        FileInputStream saveInputStream = new FileInputStream(saveFile);
//        long facePicSize = saveFile.length();
        
        

	}
	
	/**
	 * 订阅报警
	 * @Title: SubscribAlarm
	 *
	 * */
	//@Test
	public void SubscribAlarm() {
		if(loginId == null||loginId.intValue() < 1) {
			try {
				A();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		int chn = 0;//IPC通道一般为0
		NET_DVR_SUBSCRIBE_REPLY.ByReference sSmartSubscrib = new NET_DVR_SUBSCRIBE_REPLY.ByReference();
		
		int index = intelist.intelist_Vfd.ordinal();
		if(((lpDeviceInfo.function[0] & (1<<index)) >> index == 1) && (lpDeviceInfo.deviceType ==  2)){
			if(!m_SubscribFaceDetect) {
				boolean ret = DeviceSdk.INSTANCE.NET_SDK_SmartSubscrib(loginId, ErrorCodeAndConst.NET_DVR_SMART_VFD, chn, sSmartSubscrib);
				if(ret) {
					m_SubscribFaceDetect = true;
				}
			}
		}
		
		index = intelist.intelist_Vfd_Match.ordinal();
		if(((lpDeviceInfo.function[0] & (1<<index)) >> index == 1) && (lpDeviceInfo.deviceType ==  2)) {
			if(!m_SubscribFaceMatch) {
				boolean ret = DeviceSdk.INSTANCE.NET_SDK_SmartSubscrib(loginId, ErrorCodeAndConst.NET_DVR_SMART_VFD_MATCH, chn, sSmartSubscrib);
				if(ret) {
					m_SubscribFaceMatch = true;
					m_serverAddressVFD = new String(sSmartSubscrib.serverAddress);
					System.out.println(m_serverAddressVFD);
				}
			}
		}
								
	}
	/**
	 * 取消订阅报警
	 * @Title: UnSubscribAlarm
	 *
	 * */
	//@Test
	public void UnSubscribAlarm() {	
		if(m_SubscribFaceMatch) {
			int chn = 0;//IPC通道一般为0
			NET_DVR_SUBSCRIBE_REPLY.ByReference sSmartSubscrib = new NET_DVR_SUBSCRIBE_REPLY.ByReference();
			byte[] sb = m_serverAddressVFD.getBytes();
			Pointer pNativeData = new Memory(sb.length); 
			pNativeData.write(0, sb, 0, sb.length);		
			IntByReference dwResult = new IntByReference();
			boolean ret = DeviceSdk.INSTANCE.NET_SDK_UnSmartSubscrib(loginId, 2, chn, pNativeData, dwResult);
			if(ret) {
				m_SubscribFaceMatch = false;
				System.out.println("取消订阅报警成功");
			}
			// 释放内存
					long peer = Pointer.nativeValue(pNativeData);
					Native.free(peer);// 手动释放内存
					Pointer.nativeValue(pNativeData, 0);
		}
		if(m_SubscribFaceDetect) {
//			int chn = 0;//IPC通道一般为0
//			NET_DVR_SUBSCRIBE_REPLY.ByReference sSmartSubscrib = new NET_DVR_SUBSCRIBE_REPLY.ByReference();
//			byte[] sb = m_serverAddressVFD.getBytes();
//			Pointer pNativeData = new Memory(sb.length); 
//			pNativeData.write(0, sb, 0, sb.length);		
//			IntByReference dwResult = new IntByReference();
//			boolean ret = DeviceSdk.INSTANCE.NET_SDK_UnSmartSubscrib(loginId, 1, chn, pNativeData, dwResult);
//			if(ret) {
//				m_SubscribFaceMatch = false;
//				System.out.println("取消订阅报警成功");
//			}
//			// 释放内存
//					long peer = Pointer.nativeValue(pNativeData);
//					Native.free(peer);// 手动释放内存
//					Pointer.nativeValue(pNativeData, 0);
		}
		
			
	}
	//@Test
	public void setSDKMessageCallBack() throws Throwable {

		if(loginId == null||loginId.intValue() < 1) {
			try {
				A();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		if(!m_SubscribFaceMatch) {
			SubscribAlarm();
		}
		FaceAlarmCB = new SUBSCRIBE_CALLBACK_IMPL();
        // TODO 设置智能分析事件上报回调
        DeviceSdk.INSTANCE.NET_SDK_SetSubscribCallBack(FaceAlarmCB, null);
		 Scanner s = new Scanner(System.in);
	     while (s.hasNext()){
	         if(s.next().equals("q")){
	             break;
	         }
	     }    
	}
	/**
	 * 
	 * @author 8590
	 *
	 */
	//@Test
	public void DevSupport() {
		if(loginId == null||loginId.intValue() < 1) {
			try {
				A();
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		NET_SDK_DEV_SUPPORT.ByReference nsds = new NET_SDK_DEV_SUPPORT.ByReference();
		boolean ret = DeviceSdk.INSTANCE.NET_SDK_GetDeviceSupportFunction(loginId, nsds);
		if(ret) {
						
			int index = devIntelist.supportThermometry.ordinal();
			System.out.println( (nsds.support  & (1<<index)) >> index);
			
		}		
	}
	public enum devIntelist{
		supportThermometry,//口罩跟体温
        supportVfd,//人脸检测
        supportVfdMatch,//人脸比对
        supportThermal,////热成像
        supportPassLine,//过线统计
	}
	public enum intelist { 
		intelist_enable,//是否包含智能能力集列表
        intelist_Perimeter,//区域入侵
        intelist_Tripwire,//绊线侦测
        intelist_Osc,//物品看护
        intelist_Avd,//异常侦测
        intelist_Cpc,//人流量统计
        intelist_Cdd,//人群密度检测
        intelist_Ipd,//人员入侵侦测
        intelist_Vfd,//人脸抓拍
        intelist_Vfd_Match,//人脸比对
        intelist_Vehice,//车牌检测
        intelist_AoiEntry,//进入区域
        intelist_AoiLeave,//离开区域
        intelist_PassLineCount,//过线统计
        intelist_Vfd_Detect,//人脸侦测
        intelist_Traffic,//流量统计
        intelist_Thermal, //热成像测温
		};

		/**
		 * 删除A2 IPC目标信息
		 * @Title: F
		 *
		 * */
		//@Test
		public void F() {
			String id = "333";//要删除的目标id
			 String szUrl = "DeleteTargetFace";
			 String tempXML = "<?xml version = '1.0' encoding='utf-8'?>" +
	                                         "<config version='1.7' xmlns='http://www.ipc.com/ver10'>" +
	                                         "<types>" + 
	                                             "<deleteType>" + 
	                                               "<enum>byPersonID</enum>" +  
	                                               "<enum>byListType</enum>" +  
	                                               "<enum>byName</enum>" +  
	                                               "<enum>byIdentifyNumber</enum>" + 
	                                             "</deleteType>" +  
	                                             "<listType>" + 
	                                               "<enum>strangerList</enum>" +  
	                                               "<enum>whiteList</enum>" +  
	                                               "<enum>blackList</enum>" + 
	                                             "</listType>" + 
	                                           "</types>" +  
	                                           "<deleteAction>" + 
	                                             "<deleteType type='deleteType'>byName</deleteType>" +  
	                                             "<name type='string' maxLen='127'><![CDATA[333]]></name>" + 
	                                           "</deleteAction>" + 
	                                         "</config>";
			 //String sendXml = String.format(tempXML, id);
			 String sendXml = tempXML;
	        IntByReference lpBytesReturned = new IntByReference();
	        Pointer pNativeData = new Memory(1024 * 1024); 
	        
	        boolean ret = DeviceSdk.INSTANCE.NET_SDK_TransparentConfig(loginId, 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);								
				System.out.println("删除目标成功");									
	        }
	     // 释放内存
			long peer = Pointer.nativeValue(pNativeData);
			Native.free(peer);// 手动释放内存
			Pointer.nativeValue(pNativeData, 0);
		}
		//@Test
		public void G() {
			
			LPNET_SDK_CLIENTINFO.ByReference lpClientInfo = new LPNET_SDK_CLIENTINFO.ByReference();
			lpClientInfo.lChannel = 0;
			lpClientInfo.streamType = 1;
			lpClientInfo.hPlayWnd = null;
			lpClientInfo.bNoDecode = 0;
			NativeLong m_hPlayHandle = LoginModule.netsdk.NET_SDK_LivePlay(loginId, lpClientInfo, null, null);
	        
		}
}
