#================================================================
#================================================================
# API-CAN(WDM)
# CAN communication callback sample
# Set the transmit settings file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ccan
from common_function import *


#========================================
# Function name    SetTransmit
# Parameter        message_type    Transmit message type
# Parameter        can_id          Transmit CAN ID
# Parameter        data_length     Transmit message data length
# Parameter        data            Transmit data
# Details          Function that displays and processes the transmit settings set menu
# Return value     None
#========================================
def SetTransmit(message_type, can_id, data_length, data):
    message_type_can = ctypes.c_uint()         # CAN message
    message_type_can_fd = ctypes.c_uint()      # CAN FD message
    message_type_remote = ctypes.c_uint()      # Remote frame
    message_type_bitrate = ctypes.c_uint()     # Bitrate switch
    message_type_extended = ctypes.c_uint()    # Extended format
    global g_mutex_object                      # Mutex
    global g_info_flag                         # Flags message displayed in the callback

    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        message_type_string = GetMessageTypeString(message_type, 0)
        can_id_string = f"{can_id.value:X}[Hex]"
        data_length_string = f"{data_length.value:X}[Hex]"
        data_string = ""
        if data_length.value > 0:
            for i in range(0, data_length.value):
                data_string += f"{data_length.value - i - 1}:{data[0][data_length.value - i - 1]:X} "
            data_string += "[Hex]"
        else:
            data_string = "No data"
        #----------------------------------------
        # Display the setting parameter
        #----------------------------------------
        print("=========================")
        print("Transmit Setting Parameters")
        print("=========================")
        print(f"Message type    : {message_type_string}")
        print(f"CAN ID          : {can_id_string}")
        print(f"Data length     : {data_length_string}")
        print(f"Data            : {data_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("=========================")
        print("Menu (Top > Transmit Settings)")
        print("=========================")
        print("1 : Message Type Setting")
        print("2 : CAN ID Setting")
        print("3 : Data Setting")
        print("b : Back")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Unlock
        #----------------------------------------
        g_mutex_object.release()
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Lock
        #----------------------------------------
        g_mutex_object.acquire()
        #----------------------------------------
        # If message displayed in the callback, output 8 lines
        #----------------------------------------
        if g_info_flag.value == 1:
            print("\n\n\n\n\n\n\n")
            g_info_flag.value = 0
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # Message Type Setting
        #--------------------
        if buf == "1":
            print("\n----------------------------------------")
            print("Start the message type setting")
            print("----------------------------------------")
            print("----------------------------------------")
            print("Parameter(CAN message)")
            print("----------------------------------------")
            #----------------------------------------
            # Input the CAN message
            #----------------------------------------
            while True:
                print("CAN message  Not transmitted: 0 Transmitted: 1")
                print("Please input whether to transmit : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            message_type_can.value = int(buf)
            print("\n----------------------------------------")
            print("Parameter(CAN FD message")
            print("----------------------------------------")
            #----------------------------------------
            # Input the CAN FD message
            #----------------------------------------
            while True:
                print("CAN FD message  Not transmitted: 0 Transmitted: 1")
                print("Please input whether to transmit : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            message_type_can_fd.value = int(buf)
            print("\n----------------------------------------")
            print("Parameter(Remote frame)")
            print("----------------------------------------")
            #----------------------------------------
            # Input the remote frame
            #----------------------------------------
            while True:
                print("Remote frame  Not transmitted: 0 Transmitted: 1")
                print("Please input whether to transmit : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            message_type_remote.value = int(buf)
            print("\n----------------------------------------")
            print("Parameter(Bitrate switch)")
            print("----------------------------------------")
            #----------------------------------------
            # Input the bitrate switch
            #----------------------------------------
            while True:
                print("Bitrate switch  Not transmitted: 0 Transmitted: 1")
                print("Please input whether to transmit : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            message_type_bitrate.value = int(buf)
            print("\n----------------------------------------")
            print("Parameter(Extended format)")
            print("----------------------------------------")
            #----------------------------------------
            # Input the extended format
            #----------------------------------------
            while True:
                print("Extended format  Not transmitted: 0 Transmitted: 1")
                print("Please input whether to transmit : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            message_type_extended.value = int(buf)
            #----------------------------------------
            # Get the type of message transmitted
            #----------------------------------------
            message_type.value = ((ccan.CCAN_MSG_TYPE_CAN if message_type_can else 0) |
                                    (ccan.CCAN_MSG_TYPE_CAN_FD if message_type_can_fd else 0) |
                                    (ccan.CCAN_MSG_TYPE_REMOTE_FRAME if message_type_remote else 0) |
                                    (ccan.CCAN_MSG_TYPE_BITRATE_SWITCH if message_type_bitrate else 0) |
                                    (ccan.CCAN_MSG_TYPE_EXTENDED_FORMAT if message_type_extended else 0))
            message_type_string = GetMessageTypeString(message_type, 1)
            print("\nMessage Type Setting Successful completion")
            print(f"Message Type = 0x{message_type.value:02X} ({message_type_string})\n")
        #--------------------
        # CAN ID Setting
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Input the CAN ID
            #----------------------------------------
            while True:
                print("\nPlease input the CAN ID[Hex] : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 16):
                    continue
                break
            can_id.value = int(buf, 16)
            print("\nCAN ID Setting Successful completion")
            print(f"CAN ID = 0x{can_id.value:X}\n")
        #--------------------
        # Data Setting
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the data length
            #----------------------------------------
            while True:
                print("\nPlease input the data length (range is 0-8) : ", end='', flush=True)
                #----------------------------------------
                # Unlock
                #----------------------------------------
                g_mutex_object.release()
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Lock
                #----------------------------------------
                g_mutex_object.acquire()
                #----------------------------------------
                # If message displayed in the callback, output 8 lines
                #----------------------------------------
                if g_info_flag.value == 1:
                    print("\n\n\n\n\n\n\n")
                    g_info_flag.value = 0
                #----------------------------------------
                # Check the input value
                #----------------------------------------
                if False == isnum(buf, 10):
                    print("\nThe data length can be specified in the range 0 to 8. Please enter it again.")
                    continue
                if ((int(buf, 10)  < 0) or (int(buf, 10)  > 8)):
                    print("\nThe data length can be specified in the range 0 to 8. Please enter it again.")
                    continue
                break
            data_length.value = int(buf, 10)
            print("\n----------------------------------------")
            print("Start setting data")
            print("----------------------------------------")
            for i in range(0, data_length.value):
                #----------------------------------------
                # Input the data
                #----------------------------------------
                while True:
                    print(f"Please input the data{data_length.value -i -1}[Hex] : ", end='', flush=True)
                    #----------------------------------------
                    # Unlock
                    #----------------------------------------
                    g_mutex_object.release()
                    #----------------------------------------
                    # Waiting for input
                    #----------------------------------------
                    buf = input()
                    #----------------------------------------
                    # Lock
                    #----------------------------------------
                    g_mutex_object.acquire()
                    #----------------------------------------
                    # If message displayed in the callback, output 8 lines
                    #----------------------------------------
                    if g_info_flag.value == 1:
                        print("\n\n\n\n\n\n\n")
                        g_info_flag.value = 0
                    #----------------------------------------
                    # Check if the input value is a number
                    #----------------------------------------
                    if False == isnum(buf, 16):
                        continue
                    break
                data[0][data_length.value -i -1] = int(buf, 16)
            data_string = ""
            if data_length.value  > 0:
                for i in range(0, data_length.value):
                    data_string += f"{data_length.value -i -1}:{data[0][data_length.value - i - 1]:X} "
            else:
                data_string = "No data"
            print("\nData Setting Successful completion")
            print(f"Data length    = {data_length.value}")
            print(f"Data[Hex]      = {data_string}\n")
        #--------------------
        # Back
        #--------------------
        elif buf == "b":
            break
        #--------------------
        # Error Number
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    return message_type, can_id, data_length, data