import random
import sys
import time

def data1_test(gnjAPI, dngNr):

    print( "     ***** Data1 Test *****")
    time.sleep(2)

    print("      ---- Reading fields 1-15 ----")
    ret, fields = gnjAPI.read_data(1234,15,dngNr)
    if ret == 15:
        print("      --> Successfull read from data1, fields 1-15")
        for i in fields:
            print("     ", i)
    else:
        print("     ----->ReadData error",ret)
        return False

    time.sleep(2)

    print("     ---- Reading field 10-15 ----")
    ret, fields = gnjAPI.read_data_ex(1234,10,6, dngNr)
    if ret == 6:
        print("      --> Successfull read from data1 feilds 10-15")
        for i in fields:
            print("     ", i)
    else:
        print("     --->ReadDataEx error",ret)
        return False

    time.sleep(2)

    print("     ---- Setting random dat to variable field 1-10 ----")
   
    # set random numbers to variable fields 0-9
    fields = [0] * 10
    for i in range(0,10):
        fields[i] = random.randint(100000000, 0xffffffff)
        print("     field[",i+1,"]",fields[i])

    time.sleep(2)
    
    print("\n     ---- Writing variable field 1-10 to data1 filed 1-10 ----")
    ret = gnjAPI.write_data(1234, fields, dngNr)
    if ret < 1:
        print("     WriteData error",ret)
        return False

    print("     ---> Write Data ok")

    time.sleep(2)
 
    print("\n     ---- Reading again from field 1-15 ----")

    ret, fields = gnjAPI.read_data(1234,15,dngNr)
    if ret != 15:
        print("     readData error")
        return False

    print("      --> Read data ok")
    if ret == 15:
        for i in fields:
            print("     " , i & 0xFFFFFFFF)

    time.sleep(2)

    return True

def read_from_data2( gnjAPI, memsize2, dngNr ):

    data_len_bytes = bytes(4)
    ret = gnjAPI.read_data2( 1234, data_len_bytes, 0, 4, dngNr )

    if ret == 4:
        #convert bytes to int  
        data_len = int.from_bytes(data_len_bytes, byteorder=sys.byteorder)

        if data_len <= memsize2:
            data_bytes = bytes(data_len)
            ret = gnjAPI.read_data2( 1234, data_bytes, 4, data_len, dngNr )

            if ret == data_len:
                data = data_bytes.decode()
                print( "     Current Data:")
                print( "     ",data)
            else:
                print( "     Data2 read error:", ret)
                return False 
        else:
            print("     Data len is out of bound. Skip reading")

    else:
        print( "     Data2 data len read error:", ret)
        return False

    return True

def write_to_data2( gnjAPI, data, dngNr):

    data_bytes=data.encode('utf-8')

    data_len = len(data_bytes)
    data_len_bytes = data_len.to_bytes(4, byteorder='little')

    write_len = len(data_bytes)+len(data_len_bytes)
    ret = gnjAPI.write_data2(1234, data_len_bytes + data_bytes, 0, write_len, dngNr )

    if ret == -9:
        print( "\n       Cannot write to Data2. Data2 is locked!!\n")
        return True

    if ret != write_len:
        print( "     Failed to write to data2:", ret)
        return False

    return True


def data2_test(gnjAPI, dngNr):

    print( "     ***** Data2 Test *****")

    memsize2 = gnjAPI.mem_size2( dngNr)

    print("     Data2 MemSize:", memsize2, "\n")
    time.sleep(2)
    
    if read_from_data2( gnjAPI, memsize2, dngNr ) == False:
        return False

    time.sleep(2)

    try:
        data = input("\n     Enter text to write to Data2:\n")
    except KeyboardInterrupt:
        print( "\n\n   Exiting")
        return False

    if len(data) == 0:
        print("\n      Skipping writing to Data2\n")
        return True

    # write to data2
    print( "\n     Writing to Data2")
    if write_to_data2( gnjAPI, data, dngNr ) == False:
        return False
    print( "     --> Data2 write successful")
    time.sleep(2)

    print( "\n     Locking Data2")

    # lock Data2
    if 1 != gnjAPI.lock_data2( 1234, 1, 123456789, dngNr):
        print("     Failed to lock data2")

    print( "     --> Locking Data2 successful ")
    time.sleep(2)

    # try to write to data2
    print( "\n     Writing to Data2")
    if write_to_data2( gnjAPI, data, dngNr ) == False:
        return False

    time.sleep(2)

    print( "     Unlocking Data2")

    # unlock Data2
    if 1 != gnjAPI.lock_data2( 1234, 0, 123456789, dngNr):
        print("     Failed to unlock data2")

    print( "     --> Unlocking Data2 successful ")
    time.sleep(2)

    # read from data2 again
    print( "\n     Reading from data2 again\n")
    if read_from_data2( gnjAPI, memsize2, dngNr ) == False:
        return False

    time.sleep(2)

    return True