use super::mydefine::*;
pub mod spectralserver;
pub mod spectralbase;
use std::fs;
use super::mylog::*;
use serde_json::json;
use spectralserver::calibrate_file;
use std::ffi::CStr;
use std::path::Path;
pub fn delete_file(filepath: String) -> String {
    let file_path = Path::new(&filepath);
    if file_path.exists() {
        fs::remove_file(file_path).unwrap();
        "OK".to_string()
    } else {
        "文件不存在".to_string()
    }
}
pub fn sendtoport_andgetreturn(
    data: serde_json::Value,
    datatype: serde_json::Value,
) -> Result<RetStruct, String> {
    let command = data.get("command").unwrap().to_string();
    //println!("start_collect data:{}", data.to_string());
    match command.as_str() {

        "\"start_collect_flat\"" => {
            return start_collect_flat(data, datatype);
        },  

        "\"start_collect_dark\"" => {
            return start_collect_dark(data, datatype);
        },
        "\"get_sensor_info\"" => {
            spectralserver::is11_init();
            logtorust("init sensor ok".to_string());
            let sensor_info = spectralserver::is11_get_sensor_info();
            let shuttertime = spectralserver::get_shuttertime();
            let sensor_name_cstr = unsafe { CStr::from_ptr(sensor_info.SensorName.as_ptr()) };
            let sensor_name = sensor_name_cstr.to_str().unwrap();
            let serilnumber_cstr = unsafe { CStr::from_ptr(sensor_info.serialnumber.as_ptr()) };
            let serilnumber = serilnumber_cstr.to_str().unwrap();
            //定义一个json对象
            let jsonforret = json!({
                "bochangxishu":{
                    "a0":sensor_info.a1,
                    "a1":sensor_info.a2,
                    "a2":sensor_info.a3,
                    "a3":sensor_info.a4,
                },
                "serialnumber":serilnumber,
                "bandnum":sensor_info.BandNum,
                "bandsum":sensor_info.BandNum,
                
                "name":sensor_name,
                // "name":sensor_name,
                "version":"1.0.0",
                "return_data_type":0,
                "work_mode":"advanced_mode",
                "sensor_type":"IRIS-Sensor",
                "fiber_type":"Single",
                "shutter_time":shuttertime,
                "has_shutter":true,


            });
            let califiename=format!("calibratefile/{}_{}_upgain.bin",sensor_name,serilnumber);
            spectralserver::load_all_calibrate_file(califiename);
            logtorust(format!("get_sensor_info:{}", jsonforret.to_string()));
            return Ok(RetStruct {
                datatype: 0,
                content: jsonforret.to_string(),
                data: IS11DataStruct::default(),
            });
        }
        "\"start_opt\"" => {
            spectralserver::opt_sensor(90);
            let jsonforret = json!({
                "command":"start_opt"

            });
            return Ok(RetStruct {
                datatype: 0,
                content: jsonforret.to_string(),
                data: IS11DataStruct::default(),
            });
        }
        "\"get_opt\"" => {
            println!("get_opt");
            let ret = get_opt_result();
            return ret;
        }
        "\"start_collect\"" => {
            return start_collect(data, datatype);
        }

        "\"get_caiji_state\"" => {
            let (caiji_state, caiji_state_str,percent) = spectralserver::get_now_stat();
            let jsonforret = json!({
                "caiji_state":caiji_state,
                "info":caiji_state_str,
                "percent":percent,
                "return_data_type":0,
            });
            //logtorust(format!("get_caiji_state:{}", jsonforret.to_string()));
            return Ok(RetStruct {
                datatype: 0,
                content: jsonforret.to_string(),
                data: IS11DataStruct::default(),
            });
        }
        "\"get_data\"" => {
            return get_data(data, datatype);
        },
        "\"get_data_flat\"" => {
            return get_data_flat(data, datatype);
        },
        "\"get_data_dark\"" => {
            return get_data_dark(data, datatype);
        },
        "\"set_shutter_time\"" => {
            return set_shutter_time(data, datatype);
        },
        _ => {
            return Err("command not found ".to_string() + "command is:" + &command);
        }
    }


}

pub fn get_opt_result() -> Result<RetStruct, String> {
    let shuttertime = spectralserver::get_shuttertime();

    let jsonret = json!({
        "opt":shuttertime,

    });



    return Ok(RetStruct {
        datatype: 0,
        content: jsonret.to_string(),
        data: IS11DataStruct::default(),
    });
}
pub fn set_shutter_time(data: serde_json::Value,
    datatype: serde_json::Value) -> Result<RetStruct, String> {

    
        let shuttertime: u32;
        if data.get("shutter_time").is_none() {
            shuttertime = spectralserver::get_shuttertime() as u32;
        } else {
            shuttertime = data.get("shutter_time").unwrap().as_u64().unwrap() as u32;
            spectralserver::set_shutter_time(shuttertime);
        }


    let jsonret = json!({
        "shuttertime":"ok",

    });



    return Ok(RetStruct {
        datatype: 0,
        content: jsonret.to_string(),
        data: IS11DataStruct::default(),
    });
}
pub fn start_collect(
    data: serde_json::Value,
    datatype: serde_json::Value,
) -> Result<RetStruct, String> {


    let shuttertime: u32;
    if data.get("shutter_time").is_none() {
        shuttertime =spectralserver::get_shuttertime() as u32;
    } else {
        shuttertime = data.get("shutter_time").unwrap().as_u64().unwrap() as u32;
    }
    //判断是否有这个参数

    let removedark: bool;
    if data.get("remove_dark").is_none() {
        removedark = false;
    } else {
        if data.get("remove_dark").unwrap().is_boolean() {
            removedark = data.get("remove_dark").unwrap().as_bool().unwrap();
        } else if data.get("remove_dark").unwrap().is_string() {
            let remove_dark_str = data.get("remove_dark").unwrap().as_str().unwrap();
            if remove_dark_str == "yes" {
                removedark = true;
            } else {
                removedark = false;
            }
        } else {
            removedark = false;
        }
    }

    let computeflat = spectralserver::get_is_computeref();
    logtorust(format!("start_collect,shutter time is:{}", shuttertime));
    if !data.get("collect_times").is_none() {
        if data.get("collect_times").unwrap().is_u64() {
            let collect_times = data.get("collect_times").unwrap().as_u64().unwrap() as u32;
            spectralserver::set_average_number(collect_times,collect_times,collect_times );
        } 
         

        
    }


    spectralserver::collect(shuttertime, removedark, computeflat);
    let jsonret = json!({
        "command":"start_collect"

    });
    return Ok(RetStruct {
        datatype: 0,
        content: jsonret.to_string(),
        data: IS11DataStruct::default(),
    });
}

pub fn start_collect_dark(
    data: serde_json::Value,
    datatype: serde_json::Value,
) -> Result<RetStruct, String> {
    let shuttertime: u32;
    if data.get("shutter_time").is_none() {
        shuttertime = spectralserver::get_shuttertime() as u32;
    } else {
        shuttertime = data.get("shutter_time").unwrap().as_u64().unwrap() as u32;
    }
    //判断是否有这个参数
    if !data.get("collect_times").is_none() {
        if data.get("collect_times").unwrap().is_u64() {
            let collect_times = data.get("collect_times").unwrap().as_u64().unwrap() as u32;
            spectralserver::set_average_number(collect_times,collect_times,collect_times );
        }      
    }

    spectralserver::collcect_dark(shuttertime);
    let jsonret = json!({
        "command":"start_collect_dark"

    });
    return Ok(RetStruct {
        datatype: 0,
        content: jsonret.to_string(),
        data: IS11DataStruct::default(),
    });

}


pub fn start_collect_flat(
    data: serde_json::Value,
    datatype: serde_json::Value,
) -> Result<RetStruct, String> {
    let shuttertime: u32;
    if data.get("shutter_time").is_none() {
        shuttertime = spectralserver::get_shuttertime() as u32;
    } else {
        shuttertime = data.get("shutter_time").unwrap().as_u64().unwrap() as u32;
    }
    //判断是否有这个参数
    if !data.get("collect_times").is_none() {
        if data.get("collect_times").unwrap().is_u64() {
            let collect_times = data.get("collect_times").unwrap().as_u64().unwrap() as u32;
            spectralserver::set_average_number(collect_times,collect_times,collect_times );
        }      
    }

    spectralserver::collcect_flat(shuttertime);
    let jsonret = json!({
        "command":"start_collect_flat"

    });
    return Ok(RetStruct {
        datatype: 0,
        content: jsonret.to_string(),
        data: IS11DataStruct::default(),
    });

}





pub fn get_data(data: serde_json::Value, datatype: serde_json::Value) -> Result<RetStruct, String> {
    let mut is11_data = spectralserver::get_data();
    println!("get_data datatype:{}", data["return_data_type"]);
    let retrun_data_type = data["return_data_type"].as_u64().unwrap();
    if retrun_data_type ==0x12 || retrun_data_type ==0x13 {

        is11_data=calibrate_file(&is11_data)
    }

    let jsonret = json!({
        "command":"get_data"

    });

    return Ok(RetStruct {
        datatype: 2,
        content: jsonret.to_string(),
        data: is11_data,
    });
}

pub fn get_data_flat(data: serde_json::Value, datatype: serde_json::Value) -> Result<RetStruct, String> {
    let is11_data = spectralserver::get_data_flat();

    let jsonret = json!({
        "command":"get_data_flat"

    });

    return Ok(RetStruct {
        datatype: 2,
        content: jsonret.to_string(),
        data: is11_data,
    });
}

pub fn get_data_dark(data: serde_json::Value, datatype: serde_json::Value) -> Result<RetStruct, String> {
    let is11_data = spectralserver::get_data_dark();

    let jsonret = json!({
        "command":"get_data_dark"

    });

    return Ok(RetStruct {
        datatype: 2,
        content: jsonret.to_string(),
        data: is11_data,
    });
}

pub fn set_weave_coeff(
    specnumber: i32,
    a0: f64,
    a1: f64,
    a2: f64,
    a3: f64,
) -> String {
    println!("set_weave_coeff:specnumber:{},a0:{},a1:{},a2:{},a3:{}", specnumber, a0, a1, a2, a3);
    spectralserver::set_weave_coeff(specnumber, a0, a1, a2, a3);
    "OK".to_string()

}