//
// Copyright (C) 2024 Automated Design Corp.. All Rights Reserved.
// Created Date: 2024-09-17 10:51:11
// -----
// Last Modified: 2024-11-12 09:32:14
// -----
//
//

use mechutil::{
    command::{MechFsmCommandTuple, MechFsmControl, MechFsmState, MechFsmStatusTuple},
    command_arg_tuple::MechFsmCommandArgTuple,
    variant::VariantValue,
};
use serde_json::json;

/// Test conversions for MechFsmCommandTuple and MechFsmStatusTuple.
#[tokio::test]
async fn test_tuple_conversion() {
    let mut cmd_test = MechFsmCommandTuple::new();
    cmd_test.transaction_id = 32865;
    cmd_test.control = MechFsmControl::Idle;
    cmd_test.crc = 733694397;

    let var: VariantValue = cmd_test.try_into().unwrap();
    let cmd: MechFsmCommandTuple;

    match var.try_into() {
        Ok(res) => cmd = res,
        Err(err) => panic!("Converion from variant->MechFsmCommandTuple failed.{}", err),
    }

    assert_eq!(cmd.transaction_id, cmd_test.transaction_id);
    assert_eq!(cmd.control, cmd_test.control);
    assert_eq!(cmd.crc, cmd_test.crc);
    assert_eq!(cmd.data.num_rows, cmd_test.data.num_rows);

    let status = MechFsmStatusTuple::new();
    let status_json = serde_json::to_value(status).unwrap();

    assert_eq!(status_json["transaction_id"], 0);

    // If the conversion does not work properly, a panic! will occur.
    let _status_var: VariantValue = status.try_into().unwrap();
}

/// Test the CRC calculation based upon known results.
#[tokio::test]
async fn test_crc_calculation() {
    let mut arg = MechFsmCommandArgTuple::new();
    let _ = arg.push_value_f32(-293.7);
    let _ = arg.push_value_f32(-9.9);
    let _ = arg.push_value_f32(500.3);
    let _ = arg.push_value_f32(180.0);
    let _ = arg.push_value_f32(0.0);
    let _ = arg.push_value_f32(0.0);
    let _ = arg.push_value_u16(1234);
    let _ = arg.push_value_bool(true);

    let mut status_hash_test = MechFsmStatusTuple::new();
    status_hash_test.state = MechFsmState::Init;
    status_hash_test.transaction_id = 12345;
    status_hash_test.data = arg.clone();
    status_hash_test.update_crc32();
    assert_eq!(status_hash_test.crc, 2601479153);

    let mut cmd_hash_test = MechFsmCommandTuple::new();
    cmd_hash_test.transaction_id = 2000;
    cmd_hash_test.control = MechFsmControl::Idle;
    cmd_hash_test.index = 7;
    cmd_hash_test.sub_index = 9;
    cmd_hash_test.data = arg;
    cmd_hash_test.update_crc32();
    assert_eq!(cmd_hash_test.crc, 3238533793);
}
