use libc::{c_uchar, size_t};
use std::slice;

use crate::serport::serport::*;
use super::STRSensorInfo;


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" {
    pub fn Set_Serial_FUN(writefunc:SerialWrite,readfunc:SerialWrite);
    pub fn abs1(input: i32) -> i32;
    pub fn test();
    pub fn IS11SensorInit() -> i32;
    pub fn Get_SensorInfo() -> STRSensorInfo;
    pub fn IS11OptSnenser(percent:i32) -> i32;
    pub fn IS11GetData(outdata: *mut u16, shuttertime: i32) -> i32;

}

pub 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;
pub 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
}
