
use crate::genji;
use super::util;

pub fn detect( _api: &genji::Api)->i16{

    let count = _api.count();
    println!("Count={}", count);
    
    if count < 1 {
        return count;
    }

    for dng_nr in 1..count+1{

        println!("\n   ******* Genji No.{} ********", dng_nr);

        let ser = _api.sernr(dng_nr);
        println!("   Serial Number: {ser}");
        if ser < 1 {
            return -1;
        }

        let mut gusn:String = Default::default();
        if 1 == _api.gusn( &mut gusn, dng_nr) {
            println!("   GUSN: {}",gusn);
        }else{
            return -1;
        }
    }
    println!("");
    util::pause();

    count
}

pub fn led_test(_api: &genji::Api, dng_nr:i16)->bool
{
    println!("   ******* LED Test ********");

    println!("   LED Off");
    _api.set_led( 0, dng_nr);
    util::pause();

    println!("   LED Blink");
    _api.set_led( 3, dng_nr);
    util::pause();

    println!("   LED On");
    _api.set_led( -1, dng_nr);
    println!("");

    true
}

pub fn rand_test(_api: &genji::Api, dng_nr:i16)->bool
{
    println!("   ******* Random Bytes Test ********");

    let mut rand = [0u8; 16];

    for i in 0..5{
        if 1 != _api.get_rand(16, &mut rand, dng_nr) {
            println!("    get_rand error");
            return false;
        }
        println!("   {} -> {:x?}", i+1, rand);
    }

    println!("");
    util::pause();
    true
}

pub fn rtc_test( _api: &genji::Api, dng_nr:i16)->bool
{
    println!("   ******* RTC Test ********");

    let mut cur_tm = genji::tm{ tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0 };

    let ret = _api.get_time(&mut cur_tm, dng_nr);
    
    if ret == 1 {
      println!("   RTC Time = {}/{}/{} {}:{}:{}",
                cur_tm.tm_year + 1900 , cur_tm.tm_mon + 1 ,
                cur_tm.tm_mday , cur_tm.tm_hour ,
                cur_tm.tm_min , cur_tm.tm_sec);
    }
    else if ret == -10 {
      println!( "   xxx This Genji has no real time clock xxx");
    }
    else{
       println!( "   RTC error: {}", ret);
       return false;
    }    

    println!("");
    util::pause();
    true
}