package netsdk.lib;

import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.NativeLong;
import com.sun.jna.Pointer;
import com.sun.jna.Structure;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;

import netsdk.lib.DeviceSdk;
import netsdk.struct.LPNET_SDK_DEVICEINFO;
import netsdk.struct.NET_SDK_DEVICE_FUNC_IPC;
import sun.misc.BASE64Encoder;

import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.EnumSet;
import java.util.Set;

public class CommonFunctions {
	
		public static class Text {
			public enum Style { 
				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
				};
			
				public Object[] arr;
			 //Any Set could be passed in,but EnumSet is clearly best
			 public void applyStyles(Set<Style> styles) { 
			    System.out.println(styles);
			    arr = styles.toArray();
			  }
			 
			  public void test() {
		  			  
			    applyStyles(EnumSet.of(Style.intelist_enable,Style.intelist_Cpc));
			  }
			}


	public static boolean init() {
			
		System.out.println("*********************初始化******************************");
		boolean result = DeviceSdk.INSTANCE.NET_SDK_Init();
		System.out.println("result:" + result);
		return result;
	}
	
	
	public static NativeLong login(LPNET_SDK_DEVICEINFO.ByReference lpDeviceInfo) throws Throwable {
		System.out.println("*********************登录******************************");
		//NativeLong result = DeviceSdk.INSTANCE.NET_SDK_LoginEx("10.20.19.232", 9008, "admin", "123456", lpDeviceInfo, 0, null);
		NativeLong result = DeviceSdk.INSTANCE.NET_SDK_LoginEx("117.135.213.242", 9008, "admin", "slkj810018Admin", lpDeviceInfo, 0,
				null);
		System.out.println("userId:" + result);
	
		int temp = lpDeviceInfo.function[0];
		temp = 785;
		

		int a1 = (temp & (1<<0)) >> 0;
		int a = (temp & (1<<1)) >> 1;
		int b = (temp & (1<<2)) >> 2;
		int c = (temp & (1<<3)) >> 3;
		int d = (temp & (1<<4)) >> 4;
		
		
		String s = Integer.toBinaryString(temp);

		
		return result;
	} 
	
	public static void SetStructArrToPointerData(Structure[] pJavaStuArr, Pointer pNativeData) {
        long offset = 0;
        for (int i = 0; i < pJavaStuArr.length; ++i) {
            SetStructDataToPointer(pJavaStuArr[i], pNativeData, offset);
            offset += pJavaStuArr[i].size();
        }
    }
	
    public static void SetStructDataToPointer(Structure pJavaStu, Pointer pNativeData, long OffsetOfpNativeData) {
        pJavaStu.write();
        Pointer pJavaMem = pJavaStu.getPointer();
        pNativeData.write(OffsetOfpNativeData, pJavaMem.getByteArray(0, pJavaStu.size()), 0, pJavaStu.size());
    }
    

    public static void GetPointerDataToStructArr(Pointer pNativeData, Structure[] pJavaStuArr) {
        long offset = 0;
        for (int i = 0; i < pJavaStuArr.length; ++i) {
            GetPointerDataToStruct(pNativeData, offset, pJavaStuArr[i]);
            offset += pJavaStuArr[i].size();
        }
    }

    public static void GetPointerDataToStructArr(Pointer pNativeData, long OffsetOfpNativeData, Structure[] pJavaStuArr) {
        for (int i = 0; i < pJavaStuArr.length; ++i) {
            GetPointerDataToStruct(pNativeData, OffsetOfpNativeData, pJavaStuArr[i]);
            OffsetOfpNativeData += pJavaStuArr[i].size();
        }
    }
    
    public static void GetPointerDataToStruct(Pointer pNativeData, long OffsetOfpNativeData, Structure pJavaStu) {
        pJavaStu.write();
        Pointer pJavaMem = pJavaStu.getPointer();
        pJavaMem.write(0, pNativeData.getByteArray(OffsetOfpNativeData, pJavaStu.size()), 0, pJavaStu.size());
        pJavaStu.read();
    }
    
    public static int getError() {
        return DeviceSdk.INSTANCE.NET_SDK_GetLastError();
    }

    /**
     * @param inputStream
     * @param fileLen
     * @param memory
     * @return
     */
    public static boolean ReadToMemory(InputStream inputStream, long fileLen, Memory memory) {
        if (memory != Memory.NULL) {
            try (InputStream in = inputStream) {
                int buffLen = 1024;
                byte[] buffer = new byte[buffLen];
                long currFileLen = 0;
                int readLen;
                while (currFileLen < fileLen) {
                    readLen = in.read(buffer);
                    memory.write(currFileLen, buffer, 0, readLen);
                    currFileLen += readLen;
                }
                return true;
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return false;
    }
    /**
     * @Description: 根据图片地址转换为base64编码字符串
     * @Author:
     * @CreateTime:
     * @return
     */
    public static String getImageStr(String imgFile) {
        InputStream inputStream = null;
        byte[] data = null;
        try {
            inputStream = new FileInputStream(imgFile);
            data = new byte[inputStream.available()];
            inputStream.read(data);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 加密
        BASE64Encoder encoder = new BASE64Encoder();
        String retEncoder = encoder.encode(data);
        return retEncoder.replaceAll("[\\s*\t\n\r]", "");//去掉换行符，否则导致添加不成功
    }
    /**
            * 获取图片宽度
     * @param file  图片文件
     * @return 宽度
     */
    public static int getImgWidth(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getWidth(null); // 得到源图宽
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    } 
    /**
     * 获取图片高度
     * @param file  图片文件
     * @return 高度
     */
    public static int getImgHeight(File file) {
        InputStream is = null;
        BufferedImage src = null;
        int ret = -1;
        try {
            is = new FileInputStream(file);
            src = javax.imageio.ImageIO.read(is);
            ret = src.getHeight(null); // 得到源图高
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    } 
    /**
    * 获取本地图片的字节数
    * @param imgPath
    * @return
    */
    public static int pathSize(String imgPath) {     
        File file = new File(imgPath);      
        FileInputStream fis;        
        int fileLen = 0;        
        try {           
            fis = new FileInputStream(file);            
            fileLen = fis.available();      
        } 
        catch (FileNotFoundException e) 
        {           
            e.printStackTrace();                
        } catch (IOException e) 
        {           
                e.printStackTrace();        
        }       
        return fileLen;
    }
    /**
	 * 向文件写入byte[]
	 * 
	 * @param fileName 文件名
	 * @param bytes    字节内容
	 * @param append   是否追加
	 * @throws IOException
	 */
	public static void writeFileByBytes(String fileName, byte[] bytes, boolean append) throws IOException {
		try(OutputStream out = new BufferedOutputStream(new FileOutputStream(fileName, append))){
			out.write(bytes);
		}
	}

    public static String stampToDate(long lt){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);                
        return res;
    }
    public static long dateToStamp(String s) {
    	long ts = 0l;
    	try {
    		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date = simpleDateFormat.parse(s);
            ts = date.getTime()/1000;
    	}
    	catch(Exception e) {
    		
    	}
        
        return ts;
    }
    public static String GetDeviceMAC(byte[] deviceMAC)
    {
    	if (deviceMAC == null) {
            return null;
        }
        StringBuffer sb = new StringBuffer(deviceMAC.length);
        String sTmp;

        for (int i = 0; i < deviceMAC.length; i++) {
            sTmp = Integer.toHexString(0xFF & deviceMAC[i]);
            if (sTmp.length() < 2)
                sb.append(0);
            if(i < 5)
            	sb.append(sTmp + ":");
            else
            	sb.append(sTmp);
            
        }

        return sb.toString();


    }
    /***
     * 把byte数组后面为0的元素全部去掉
     * @param src
     * @return
     */   
    public static byte[] RemoveZero(byte[] src)
    {
   	 byte[] resList = null;   	 
   	 int len = 0;
        for (int i = 0; i < src.length; i++)
        {
            if (src[i] != 0)
           	 len++;
            else
                break;
        }
        if(len > 0) {
       	 resList = new byte[len];
            System.arraycopy(src, 0, resList, 0, len);
        }        
        return resList;
    }
    public static String ByteToStr(byte[] src,String encode)
    {
   	 String res = "";
   	 byte[] dst = RemoveZero(src);
   	 if(dst!= null) {
   		 try {
   			 
   				//res = new String(RemoveZero(src),"UTF8");
   				//res = new String(RemoveZero(src),"GB2312");
   				res = new String(RemoveZero(src),encode);
   			 }
   			 catch (UnsupportedEncodingException ee){							
   			 }
   	 }
		 
        return res;
    }
    /***
     * 释放申请的内存指针
     * @param pt
     * @return
     */   
    public static void FreePointer(Pointer pt) {
    	long peer = Pointer.nativeValue(pt);
		Native.free(peer);// 手动释放内存
		Pointer.nativeValue(pt, 0);
    }
}
