// Prevents additional console window on Windows in release, DO NOT REMOVE!!
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod irisdatamanager;
mod algorithm;
mod mylog;
mod serport;
mod iris_spectral;
mod irishypersptral;
mod mydefine;
mod comman1;
mod myformatiris;
use comman1::*;
use algorithm::interpolate_spline;
use algorithm::sg_smooth;
use mydefine::*;
use iris_spectral::spectralbase::Senortype;
use myformatiris::getoneirisfile;
enum DevName {
    IRIS_IS11,
    IRIS_SENSOR(Senortype),
    
}

use lazy_static::lazy_static;
use tauri::api::dir;
use std::sync::Mutex;
//设置一个可修改的全局变量
lazy_static! {
    static ref DEVNAME: Mutex<DevName> = Mutex::new(DevName::IRIS_SENSOR(Senortype::IS3));
}

#[tauri::command]
 fn setport(data: serde_json::Value) -> String {
    //判断是否存在portname和baudrate
    if !data.is_object() {
        return String::from("Invalid data");
    }
    if !data["portname"].is_string() || !data["baudrate"].is_u64() {
        return String::from("Invalid data");
    }
    let portname = data["portname"].as_str().unwrap();
    let baudrate = data["baudrate"].as_u64().unwrap() as u32;
    serport::serport::set_port_info(&portname.to_string(), baudrate);
    //println!("{}",readdatafromport(1000));
    String::from("Port set ok")
}
/*      let data = {
        gain: Gain,
        direction: direction,
        filepath: Filepath,        
        DNData: DNData,
        LampData: Lampdata,
        Devinfo: Devinfo
      } */
#[tauri::command]
fn savecalibratefileIRIS(Gain:serde_json::Value,direction: bool, filepath: String, dndata: serde_json::Value, lampdata: serde_json::Value, devinfo: serde_json::Value) -> String {
    //输出 输入参数
    // println!("Gain: {:?}", Gain);
    // println!("direction: {:?}", direction);
    // println!("Filepath: {:?}", devinfo);
    // println!("DNData: {:?}", dndata);
    // println!("Lampdata: {:?}", lampdata);
    // println!("Devinfo: {:?}", devinfo);



    irisdatamanager::savecalibratefileIRIS(Gain, direction, filepath, dndata, lampdata, devinfo)
    
}


#[tauri::command]
fn savecalibratefile(gain: Vec<f32>, shutter: u32, direction: bool, filepath: String) -> String {
    let devname=DEVNAME.lock().unwrap();
    match *devname {
        DevName::IRIS_IS11=>{
            return irishypersptral::savecalibratefile_iris(gain, shutter, direction, filepath);
        },
        DevName::IRIS_SENSOR(sensor_type)=>{
            return irishypersptral::savecalibratefile_iris(gain, shutter, direction, filepath);
           //return  jianzhiis11::s(gain, shutter, direction, filepath);
        }
        
    }
    //irishypersptral::savecalibratefile_iris(gain, shutter, direction, filepath)
}

#[tauri::command]
fn sendcalibratetodev(gain: Vec<f32>, shutter: u32, direction: u32) -> String {
    let devname=DEVNAME.lock().unwrap();
    println!("sendcalibratetodev");
    match *devname {
        DevName::IRIS_IS11=>{
            return irishypersptral::sendcalibratetodev_iris(gain, shutter, direction !=0);
        },
        DevName::IRIS_SENSOR(sensor_type)=>{
            return irishypersptral::sendcalibratetodev_iris(gain, shutter, direction !=0);
           //return  jianzhiis11::s(gain, shutter, direction, filepath);
        }
        
    }



    //irishypersptral::sendcalibratetodev_iris(gain, shutter, direction)
}




#[tauri::command]
fn setdevtype(devtype: String)->String {
    let mut devname1 = DEVNAME.lock().unwrap();
    match devtype.as_str() {
        "IRIS-IS11" => *devname1 = DevName::IRIS_IS11,
        "IS3" => *devname1 = DevName::IRIS_SENSOR(Senortype::IS3),
        "IS11" => *devname1 = DevName::IRIS_SENSOR(Senortype::IS11),
        _ => *devname1 = DevName::IRIS_SENSOR(Senortype::IS3),
    }
    mylog::logtorust("set dev to ".to_string()+&devtype);
    return "ok".to_string();
}





#[tauri::command]
fn __sendto_portbinary(data: Vec<u8>, command: u8) -> String {
    irishypersptral::sendtoportbinary_iris(data, command)
}

#[tauri::command]
fn sendtoport(data: serde_json::Value, datatype: serde_json::Value) -> String {
   irishypersptral::sendtoport_iris(data, datatype)
}

#[tauri::command]
fn readformport(commanid: serde_json::Value, wait_time_json: serde_json::Value) -> String {
  irishypersptral::readformport_iris(commanid, wait_time_json)
}
#[tauri::command]
fn set_weave_coeff(specnumber: i32, a0: f64, a1: f64, a2: f64, a3: f64) -> String {
    let devname=DEVNAME.lock().unwrap();
    match *devname{
        DevName::IRIS_SENSOR(sensor_type) =>{
            iris_spectral::set_weave_coeff(specnumber, a0, a1, a2, a3);
        }  ,
        _ => {},
    }
    "OK".to_string()
}

#[tauri::command]
 fn opencom(portname: serde_json::Value, baudrate: serde_json::Value) -> String {
    //tauri
    let portname = portname.as_str().unwrap();
    let devname=DEVNAME.lock().unwrap();
    let mut baudrate :u32=0;
    match *devname {
        DevName::IRIS_IS11=>{
             baudrate =115200 as u32;
        },
        DevName::IRIS_SENSOR(sensor_type)=>{
            baudrate =921600 as u32;

        }
        
    }

   // let baudrate = baudrate.as_u64().unwrap() as u32;
    serport::serport::set_port_info(&portname.to_string(), baudrate);

    println!("opencom portname:{} baudrate:{}", portname, baudrate);
    mylog::logtorust(format!(
        "opencom portname:{} baudrate:{}",
        portname, baudrate
    ));
    serport::serport::tryuseport()
}
#[tauri::command]
fn sendtoport_andgetreturn(
    data: serde_json::Value,
    datatype: serde_json::Value,
) -> Result<RetStruct, String> {
    //irishypersptral::sendtoport_andgetreturn_iris(data, datatype)
    //irishypersptral::sendtoport_andgetreturn_iris(data, datatype)
    let devname=DEVNAME.lock().unwrap();
    match *devname {
        DevName::IRIS_IS11=>{
            return irishypersptral::sendtoport_andgetreturn_iris(data, datatype);
        },
        DevName::IRIS_SENSOR(sensor_type)=>{
            return iris_spectral::sendtoport_andgetreturn(data, datatype);
        }
        
    }


    //jianzhiis11::sendtoport_andgetreturn(data, datatype)
   
}
#[tauri::command]
fn delete_file_by_path(filepath: String) -> String {
    let devname=DEVNAME.lock().unwrap();
    match *devname {
        DevName::IRIS_IS11=>{
            "delete_file_by_path_iris(filepath)".to_string()
        },
        DevName::IRIS_SENSOR(sensor_type)=>{
            return iris_spectral::delete_file(filepath)
        }
    }
        
    
}

#[tauri::command]
fn save_reflectance_to_iris(reflectance_data: serde_json::Value, devinfo: serde_json::Value, filepath: String) -> String {
    irisdatamanager::save_reflectance_to_iris(reflectance_data, devinfo, filepath)
}

////////////////////////////////////////////////////////////////////////////////////////
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command

use tauri::{LogicalSize, Manager, Size};

fn main() {
    // 使用宏生成处理程序列表
    mylog::initlog();
    mylog::logtorust("welecome to rust log");
    mylog::logtojs("welecome to rust log");

    tauri::Builder::default()
        .invoke_handler(tauri::generate_handler![
            clearportbuff,
            greet,
            getportnames,
            opencom,
            closecome,
            sendtoport_andgetreturn,
            readformport,
            sendtoport,
            interpolate_spline,
            sg_smooth,
            savecalibratefile,
            savecalibratefileIRIS,
            sendcalibratetodev,
            setdevtype,
            set_weave_coeff,
            delete_file_by_path,
            algorithm::gaussian_filter_high,
            algorithm::interpolate_spline_at_points,
            algorithm::find_peek,
            algorithm::compute_weave_coeff,
            getoneirisfile,
            save_reflectance_to_iris
        ])
        .setup(|app| {



            let config = app.config();
           
 
            // 打印配置信息，例如窗口标题
            let producnaem = config.package.product_name.clone().unwrap();
            let version=config.package.version.clone().unwrap();
            println!("producnaem:{:?}", producnaem);
            let main_window = app.get_window("main").unwrap();
            main_window.set_title(&(producnaem+"_v"+&version));

            // 获取屏幕大小
            if let Some(monitor) = main_window.primary_monitor().unwrap() {
                let scale_factor = monitor.scale_factor();
                let physical_size = monitor.size();
                let logical_width = physical_size.width as f64 / scale_factor;
                let logical_height = physical_size.height as f64 / scale_factor;
                let new_width = logical_width * 0.8;
                let new_height = logical_height * 0.8;

                // 设置窗口大小为屏幕大小的 80%
                main_window
                    .set_size(Size::Logical(LogicalSize {
                        width: new_width,
                        height: new_height,
                    }))
                    .unwrap();

                main_window.set_cursor_visible(true).unwrap();
            }

            Ok(())
        })
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}
