use libc::{c_uchar,c_char,c_long,c_float, size_t};
use std::ffi::CStr;
use std::slice;

use super::super::serport::serport::*;
#[repr(C)]
pub struct STRSensorInfo {
 pub   SensorName: [c_char; 100],
 pub  maxValue: c_long,
 pub   BandNum: c_long,
 pub   serialnumber: [c_char; 100],
 pub  a1: c_float,
 pub a2: c_float,
 pub  a3: c_float,
 pub  a4: c_float,
 pub  issensorinit: c_uchar,
}

impl Default for STRSensorInfo {
    fn default() -> Self {
        STRSensorInfo {
            SensorName: [0; 100],
            maxValue: 0,
            BandNum: 0,
            serialnumber: [0; 100],
            a1: 0.0,
            a2: 0.0,
            a3: 0.0,
            a4: 0.0,
            issensorinit: 0,
        }
    }
    
}


type SerialWrite = Option<unsafe extern "C" fn(data: *mut c_uchar, length: size_t) -> size_t>;
#[cfg_attr(target_os = "windows", link(name = "..\\myis11\\project\\is11\\cmake-build-release-visual-studio-2022/is11lib", kind = "dylib"))]
#[cfg_attr(target_os = "linux", link(name = "is11lib", kind = "dylib"))]
//#[link(name = "../myis11/project/is11/cmake-build-release-visual-studio-2022/is11lib",kind = "dylib")]
extern "C" {
    fn Set_Serial_FUN(writefunc:SerialWrite,readfunc:SerialWrite);
    fn abs1(input: i32) -> i32;
    fn test();
    fn IS11SensorInit() -> i32;
    fn Get_SensorInfo() -> STRSensorInfo;
    fn IS11OptSnenser(percent:i32) -> i32;
    fn IS11GetData(outdata: *mut u16, shuttertime: i32) -> i32;

}

unsafe extern "C" fn serialsenddata(data: *mut c_uchar, length: size_t) -> size_t {
    // 处理数据
    let data_slice = slice::from_raw_parts(data, length as usize).to_vec();
    // data_slice转换为Vec<u8>

    // 打印数据
    // for byte in data_slice.clone() {
    //     print!("{:02X} ", byte);
    // }
    // println!();
    sendtoprot(data_slice);
    length
}
use core::ptr;
unsafe extern "C" fn serialreaddate(data: *mut c_uchar, length: size_t) -> size_t {

    let  dataout=readforport();
    let length1: usize = dataout.len();
    // 将结果复制给c_uchar
    // for byte in dataout.clone() {
    //     print!("{:02X} ", byte);
    // }
    // println!();
    
    ptr::copy_nonoverlapping(dataout.as_ptr(), data, length1);
   // println!("{:?}",data);
    length1
}

pub fn is11_init() -> i32 {
    unsafe {
        Set_Serial_FUN(Some(serialsenddata), Some(serialreaddate));
        IS11SensorInit()
    }
}

pub fn is11_get_sensor_info() -> STRSensorInfo {
    unsafe { Get_SensorInfo() }
}

pub fn _is11_opt_snenser(percent: i32) -> i32 {
    unsafe { IS11OptSnenser(percent) }
}

pub fn is11_get_data(shuttertime: i32) -> Vec<u16> {
    let mut outdata: Vec<u16> = vec![0; 2048];

    unsafe {

        let len = IS11GetData(outdata.as_mut_ptr(), shuttertime);
        outdata.truncate(len as usize);


    }

    outdata
}
