import logging
import re


from leo_grifo_io_box import theBrainBox
from leo_grifo_common import *
import builtins
from datetime import datetime
from leo_grifo_test_report import testReport

def exit_due_to_critical_error(session_name, reason='Fatal error found !!!',elapsed_time=0):
    logging.error(f'*** ERROR *** {reason}. Exit ...')    
    close_session(session_name)
    generate_pdf_report('',elapsed_time)
    exit(-1)


def try_num(n: AnyStr) -> object:
    try:
        f = float(n)
    except Exception:
        return n
    return f

def get_test_name(file):
    base = os.path.basename(file)    
    return base[:base.rfind('.')]

### ----- power utilities -----------------------------
def power_grifo_on(wait_after=0, wait_before=0):    
    time.sleep(wait_before)
    setValue(theBrainBox,True,'MAIN_POWER')
    ret,err = check(theBrainBox,1,'MAIN_POWER')

    time.sleep(wait_after)
    return ret

def power_grifo_off(wait_after=0, wait_before=0):    
    time.sleep(wait_before)
    setValue(theBrainBox,False,'MAIN_POWER')
    ret,err = check(theBrainBox,0,'MAIN_POWER',timeout=0.1)  
    time.sleep(wait_after)          
    return ret  


def startTest():
    now = datetime.now()
    add_text_log(f"Start Time: {now}")
    return now


def stopTest():
    now = datetime.now()
    add_text_log(f"Stop Time: {now}")
    return now


def startTime():
    start_time = datetime.now()
    return start_time


def stopTime():
    stop_time = datetime.now()
    return stop_time


def verifyTimingReq(start_time, stop_time, expected_time):
    common_desc = 'Check the start-up within {} seconds'.format(expected_time)
    expected = None
    error_desc = ''
    real_time = stop_time - start_time
    real_time = real_time.total_seconds()
    logging.info(common_desc)
    if real_time <= expected_time:
        logging.info('OK: execution time = {} seconds'.format(real_time))
        theRecorder.add_step(common_desc, True, None, '{}'.format(real_time))
    else:
        error_desc = ' Execution Time = {} seconds is not the expected result'.format(real_time)
        logging.error(error_desc)
        theRecorder.add_step(common_desc, False, error_desc, '{}'.format(real_time))