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

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

//void IS3SetShutterOpen(int isopen);
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\\is3\\cmake-build-debug-visual-studio/iris_is3lib", kind = "dylib"))]
#[cfg_attr(target_os = "linux", link(name = "iris_is3lib", kind = "dylib"))]
// #[link(
//     name = "..\\myis11\\project\\is3\\cmake-build-debug-visual-studio/iris_is3lib",
//     kind = "dylib"
// )]
extern "C" {
    pub fn IS3Set_Serial_FUN(writefunc:SerialWrite,readfunc:SerialWrite);
    pub fn IS3SensorInit() -> i32;
    pub fn IS3Get_SensorInfo() -> STRSensorInfo;
    pub fn IS3OptSnenser(percent:i32) -> i32;
    pub fn IS3GetData(outdata: *mut u16, shuttertime: i32) -> i32;
    pub fn IS3SetWeaveLenthCoeff(a:*mut f64,length:i32) -> i32;
    pub fn IS3SetShutterOpen(isopen: 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 is3_init() -> i32 {
    unsafe {
        IS3Set_Serial_FUN(Some(serialsenddata), Some(serialreaddate));
        IS3SensorInit()
    }
}

pub fn is3_get_sensor_info() -> STRSensorInfo {
    unsafe { IS3Get_SensorInfo() }
}

pub fn is3_opt_snenser(percent: i32) -> i32 {
    unsafe { IS3OptSnenser(percent) }
}

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

    unsafe {

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


    }

    outdata
}
pub fn is3_set_shutter_open(isopen: i32) {
    unsafe { IS3SetShutterOpen(isopen) }
}

pub fn is3_set_weave_length_coeff(a: Vec<f64>) -> i32 {
    let mut a = a.clone();
    let a_ptr = a.as_mut_ptr();
    let length = a.len() as i32;
    println!("a_ptr: {:?}", a_ptr);
    println!("length: {:?}", length);
    unsafe { IS3SetWeaveLenthCoeff(a_ptr, length) }
}
