#![allow(non_snake_case)]
mod components;

use std::error::Error;

use components::main_window::MainWindow;
use components::states::MainState;
use plate_tool_lib::csv::*;
use yew::prelude::*;

#[cfg(debug_assertions)]
use plate_tool_lib::*;

#[function_component]
pub fn App() -> Html {
    html! {
        <MainWindow />
    }
}

#[cfg(debug_assertions)]
pub fn plate_test() {
    let source = plate::Plate::new(plate::PlateType::Source, plate::PlateFormat::W96);
    let destination = plate::Plate::new(plate::PlateType::Destination, plate::PlateFormat::W384);

    let transfer = transfer_region::TransferRegion {
        source_plate: source,
        source_region: transfer_region::Region::Rect((1, 1), (2, 2)),
        dest_plate: destination,
        dest_region: transfer_region::Region::Rect((2, 2), (11, 11)),
        interleave_source: (1, 1),
        interleave_dest: (3, 3),
    };
    println!("{}", transfer);
    let sws = transfer.get_source_wells();
    let m = transfer.calculate_map();
    for w in sws {
        println!("{:?} -> {:?}", w, m(w));
    }
}

pub fn state_to_csv(state: &MainState) -> Result<String, Box<dyn Error>> {
    let mut records: Vec<TransferRecord> = Vec::new();
    for transfer in &state.transfers {
        let src_barcode = state
            .source_plates
            .iter()
            .find(|spi| spi.get_uuid() == transfer.source_id)
            .ok_or("Found unpurged transfer")?;
        let dest_barcode = state
            .destination_plates
            .iter()
            .find(|dpi| dpi.get_uuid() == transfer.dest_id)
            .ok_or("Found unpurged transfer")?;
        records.append(&mut transfer_to_records(
            transfer,
            &src_barcode.name,
            &dest_barcode.name,
        ))
    }
    records_to_csv(records)
}
