use std::fs::File;
use std::io::{self, Write, Result};
use std::vec;
use serde_json::json;

// use crate::write;

use super::structures::{TimeStruct, SpectralData, ImageInfo,OneIRISData};

// Internal writer functions remain the same
fn write_time<W: Write>(time: &TimeStruct, writer: &mut W) -> Result<()> {
    writer.write_all(&[time.time_zone as u8])?;
    writer.write_all(&time.year.to_le_bytes())?;
    writer.write_all(&[time.month])?;
    writer.write_all(&[time.day])?;
    writer.write_all(&[time.hour])?;
    writer.write_all(&[time.minute])?;
    writer.write_all(&[time.second])?;
    writer.write_all(&time.millisecond.to_le_bytes())?;
    Ok(())
}


pub fn write_image_info<W: Write>(info: &ImageInfo, writer: &mut W) -> Result<()> {
    // Write data length
    writer.write_all(&info.data_length.to_le_bytes())?;

    // Write name (fixed size 100 bytes)
    let mut name_buf = [0u8; 100];
    let name_bytes = info.name.as_bytes();
    name_buf[..info.name.len().min(99)].copy_from_slice(name_bytes[0..name_bytes.len().min(99)].as_ref());
    writer.write_all(&name_buf)?;

    // Write collection time
    write_time(&info.collection_time, writer)?;

    // Write info type
    writer.write_all(&[info.info_type])?;

    // Write image data
    writer.write_all(&info.image_data)?;

    Ok(())
}



pub fn write_spectral_data<W: Write>(data: &SpectralData, writer: &mut W) -> Result<()> {
    // Write fixed-size fields
    let mut name_buf = [0u8; 100];

    let namebyte= data.name.as_bytes();
    name_buf[..data.name.len().min(99)].copy_from_slice(namebyte[0..namebyte.len().min(99)].as_ref());
    writer.write_all(&name_buf)?;

    let mut sensor_buf = [0u8; 50];
    let sensor_id_bytes = data.sensor_id.as_bytes();
    sensor_buf[..data.sensor_id.len().min(49)].copy_from_slice(sensor_id_bytes[0..sensor_id_bytes.len().min(49)].as_ref());
    writer.write_all(&sensor_buf)?;
    writer.write_all(&[data.fiber_id])?;

    write_time(&data.collection_time, writer)?;
    writer.write_all(&data.exposure.to_le_bytes())?;
    writer.write_all(&data.gain.to_le_bytes())?;
    writer.write_all(&[data.data_type])?;
    writer.write_all(&[data.pixel_size])?;
    writer.write_all(&[data.ground_type])?;
    writer.write_all(&data.bands.to_le_bytes())?;
    writer.write_all(&[data.valid_flag])?;
    
    // // Write the length of the spectral_data vector
    // writer.write_all(&(data.spectral_data.len() as u64).to_le_bytes())?;
    // Write the spectral_data vector
    writer.write_all(&data.spectral_data)?;

    Ok(())
}
pub fn caculate_spectral_data_length(data: &Vec<SpectralData>) -> u64 {
    let mut lenth:u64 = 0;
    //加上u16的长度
    lenth += 2; // bands
    //加上u8的长度
   // let numberofspectral=data.len();
    for datatemp in data  {
        lenth += 100; // name
        lenth += 50; // sensor_id
        lenth += 1 ; // fiber_id
        lenth += 10; // time_zone
        lenth += 8; // exposure
        lenth += 4; // gain
        lenth += 1; // data_type
        lenth += 1; // pixel_size
        lenth += 1; // ground_type
        lenth += 2; // bands
        lenth += 1; // valid_flag
        lenth += datatemp.spectral_data.len() as u64;
        
    }
    lenth

}
pub fn caculate_image_info_length(data: &Vec<ImageInfo>) -> u64 {
    let mut lenth: u64 = 0;
    if data.is_empty() {
        return lenth;
    }
    lenth +=2;
    for info in data {
        lenth += 8; // data_length
        lenth += 100; // name
        lenth += 10; // time_zone
        lenth += 1; // info_type
        lenth += info.image_data.len() as u64; // image_data length
    }
    lenth
}


pub fn cacluate_other_info_length(data: &Vec<serde_json::Value>) -> (Vec<u8>, u64) {
    let mut lenth: u64 = 0;
    let mut vecback= Vec::new();
    if data.is_empty() {
        return (vecback, lenth);
    }
    // for info in data {
    //     lenth+=1; // info_type
    //     lenth+=8; // data length
    //     lenth += info.data.len() as u64; // data length
    //     vecback.push(info.info_type);
    //     vecback.extend_from_slice(&(info.data.len() as u64).to_le_bytes());
    //     vecback.extend_from_slice(&info.data);
    // }
    (vecback, lenth)
}

pub fn caculate_spectral_info_length(data: &Vec<serde_json::Value>) -> (Vec<u8>, u64) {
    let mut lenth: u64 = 0;
    let mut vecback= Vec::new();
    if data.is_empty() {
        return (vecback, lenth);
    }



    lenth+=2; // sensor_id
    let lenthofinfo=data.len() as u16;
    vecback.extend_from_slice(&lenthofinfo.to_le_bytes()); // Number of spectral info entries


    for info in data {
        lenth+=2;
        lenth+=1;
        let mut lenthofthisinfo:u16=0;
        let json=info;
        let json_string = serde_json::to_string(&json).unwrap();
        let json_bytes = json_string.as_bytes();
        lenthofthisinfo= json_bytes.len() as u16+1;
        lenth += lenthofthisinfo as u64 ; 
        
        // 将长度转换为字节并添加到 vecback
        vecback.extend_from_slice(&lenthofthisinfo.to_le_bytes());
        vecback.push(0x00); // json 标识
        vecback.extend_from_slice(json_bytes);  
        vecback.push(0x00); // 添加一个字节的0x00    
    }
    (vecback, lenth)

}
pub fn wirte_iris_data(data:&OneIRISData,filepath:&str) -> Result<()> {
    let mut file = File::create(filepath)?;
    //写入光谱数据header
    let SPectralData_Flag:u32=0x00FF00FF;
    file.write_all(&SPectralData_Flag.to_le_bytes())?;
    let mut sectionlenth: u64 = caculate_spectral_data_length(&data.spectral_data_section);
    file.write_all(&(sectionlenth).to_le_bytes())?; // Section length
    let numberofspectral=data.spectral_data_section.len() as u16;
    file.write_all(&numberofspectral.to_le_bytes())?; // Number of spectral data entries 
    // Write spectral data section
    for spectral_data in &data.spectral_data_section {
        write_spectral_data(spectral_data, &mut file)?;
    }

    // Write section length
    
    // Write spectral info section
    let spectral_info_flag: u32 = 0xFF00FF00;
  

    let (spectral_info_vec, spectral_info_length) = caculate_spectral_info_length(&data.spectral_info_section);
      file.write_all(&spectral_info_flag.to_le_bytes())?; // Spectral info 区块标识
    file.write_all(&spectral_info_length.to_le_bytes())?; // Section length 
    if spectral_info_length != 0 {
           file.write_all(&spectral_info_vec)?; // Write the spectral info section data
        
    }

    let other_info_flag: u32 = 0xF0F0F0F0;
    let (other_info_vec, other_info_length) = cacluate_other_info_length(&data.other_info_section);
    file.write_all(&other_info_flag.to_le_bytes())?; // Other info 区块标识
    file.write_all(&other_info_length.to_le_bytes())?; // Section length
    if other_info_length != 0 {
        file.write_all(&other_info_vec)?; // Write the other info section data
    }

    

    let image_info_flag: u32 = 0x0F0F0F0F;
    file.write_all(&image_info_flag.to_le_bytes())?; // Image info 区块标识
    let image_info_length = caculate_image_info_length(&data.image_info_section);
    file.write_all(&image_info_length.to_le_bytes())?; // Section length
    if image_info_length != 0 {
        let numberofimageinfo = data.image_info_section.len() as u16;
        file.write_all(&numberofimageinfo.to_le_bytes())?; // Write the image info section data
            // Write image info section
         for image_info in &data.image_info_section {
           write_image_info(image_info, &mut file)?;
        }
    }

    
    Ok(())
}