#================================================================
#================================================================
# C-WaveformGenerator
# FileOperation
# main file
#                                                CONTEC Co., Ltd.
#================================================================
#================================================================
#----------------------------------------
# Import modules
#----------------------------------------
import ctypes
import ctypes.wintypes
import sys
import cgen_api
from CommonFunction import *


#========================================
# Function name    main
# Parameter        None
# Details          Function that performs main processing
# Return value     None
#========================================
def main():
    device_name = ctypes.create_string_buffer(256)    # Device name
    error_buf = ctypes.create_string_buffer(256)      # Error code string
    lret = ctypes.c_long()                            # For return code
    appid = ctypes.c_short()                          # ID for device access
    open_mode = ctypes.c_ushort()                     # Screen size
    file_path = ctypes.create_string_buffer(256)      # File path
    ao_channel = ctypes.c_ushort()                    # Channel
    wave_type = ctypes.c_ushort()                     # Waveform type
    param = ctypes.c_short()                          # Parameter (single or multiple)
    status = ctypes.c_ulong()                         # Status


    #----------------------------------------
    # Loop that wait input
    #----------------------------------------
    while True:
        #----------------------------------------
        # Get setting parameters
        #----------------------------------------
        #--------------------
        # Get the device name
        #--------------------
        lret.value = cgen_api.GenGetDeviceName(appid, device_name)
        if lret.value != 0:
            device_name_string = "-"
        else:
            device_name_string = device_name.value.decode('sjis')
        #----------------------------------------
        # Display the setting parameters
        #----------------------------------------
        print("========================================")
        print("Setting Parameter")
        print("========================================")
        print(f"Device Name : {device_name_string}")
        #----------------------------------------
        # Display the command
        #----------------------------------------
        print("========================================")
        print("Menu")
        print("========================================")
        print(" 1 : GenOpenApplication")
        print(" 2 : GenSetDeviceName")
        print(" 3 : GenExportSettingFile")
        print(" 4 : GenImportSettingFile")
        print(" 5 : GenSetWaveType")
        print(" 6 : GenSetArbitraryDataFile")
        print(" 7 : GenGetArbitraryDataFile")
        print(" 8 : GenSaveDataFile")
        print(" 9 : GenStartOperation")
        print("10 : GenGetApplicationStatus")
        print("11 : GenStopOperation")
        print("12 : GenCloseApplication")
        print(" q : Quit")
        print("Please input the command : ", end='', flush=True)
        #----------------------------------------
        # Waiting for input
        #----------------------------------------
        buf = input()
        #----------------------------------------
        # Distinguish the command
        #----------------------------------------
        #--------------------
        # GenOpenApplication
        #--------------------
        if buf == "1":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            device_name.value = buf.encode()
            #----------------------------------------
            # Input the screen size
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Screen size)")
            print("----------------------------------------")
            print("0 : Minimize")
            print("1 : Normal")
            print("2 : Maximize")
            while True:
                print("Please select the screen size : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            open_mode = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Initialize the application
            #----------------------------------------
            lret.value = cgen_api.GenOpenApplication(device_name, ctypes.byref(appid), open_mode)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenOpenApplication Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetDeviceName
        #--------------------
        elif buf == "2":
            #----------------------------------------
            # Input the device name
            #----------------------------------------
            print("\nPlease input the device name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            device_name.value = buf.encode()
            #----------------------------------------
            # Set the device name
            #----------------------------------------
            lret.value = cgen_api.GenSetDeviceName(appid, device_name.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetDeviceName Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenExportSettingFile
        #--------------------
        elif buf == "3":
            #----------------------------------------
            # Input the setting file name
            #----------------------------------------
            print("\nPlease input the setting file name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # Save the settings to ini file
            #----------------------------------------
            lret.value = cgen_api.GenExportSettingFile(appid, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenExportSettingFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenImportSettingFile
        #--------------------
        elif buf == "4":
            #----------------------------------------
            # Input the setting file name
            #----------------------------------------
            print("\nPlease input the setting file name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # Load the settings from ini file
            #----------------------------------------
            lret.value = cgen_api.GenImportSettingFile(appid, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenImportSettingFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetWaveType
        #--------------------
        elif buf == "5":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            while True:
                print("Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Input the wave type
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Wave type)")
            print("----------------------------------------")
            print("0 : Sinewave")
            print("1 : Constant")
            print("2 : Triangular")
            print("3 : Ramp")
            print("4 : Square")
            print("5 : Noise")
            print("6 : Arbitrary")
            while True:
                print("Please select the wave type : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            wave_type = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Set the wave type
            #----------------------------------------
            lret.value = cgen_api.GenSetWaveType(appid, ao_channel, wave_type)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetWaveType Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenSetArbitraryDataFile
        #--------------------
        elif buf == "6":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            while True:
                print("Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Input the data file name
            #----------------------------------------
            print("\nPlease input the data file name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # Set the data file path
            #----------------------------------------
            lret.value = cgen_api.GenSetArbitraryDataFile(appid, ao_channel, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSetArbitraryDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenGetArbitraryDataFile
        #--------------------
        elif buf == "7":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            while True:
                print("Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Get the data file path
            #----------------------------------------
            lret.value = cgen_api.GenGetArbitraryDataFile(appid, ao_channel, file_path.value)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenGetArbitraryDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}")
            if lret.value == 0:
                print(f"Data File Name = {file_path.value.decode('sjis')}")
            print("")
        #--------------------
        # GenSaveDataFile
        #--------------------
        elif buf == "8":
            #----------------------------------------
            # Input the channel number
            #----------------------------------------
            print("")
            while True:
                print("Please input the channel number(0-15) : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            ao_channel = ctypes.c_ushort(int(buf))
            #----------------------------------------
            # Input the data file name
            #----------------------------------------
            print("\nPlease input the data file name : ", end='', flush=True)
            #----------------------------------------
            # Waiting for input
            #----------------------------------------
            buf = input()
            file_path.value = buf.encode()
            #----------------------------------------
            # Input the save data count
            #----------------------------------------
            print("\n----------------------------------------")
            print("Parameter(Save data count)")
            print("----------------------------------------")
            print("0 : Single channel")
            print("1 : Multiple channels")
            while True:
                print("Please select the save data count : ", end='', flush=True)
                #----------------------------------------
                # Waiting for input
                #----------------------------------------
                buf = input()
                #----------------------------------------
                # Check if the input value is a number
                #----------------------------------------
                if False == isnum(buf, 10):
                    continue
                break
            param = ctypes.c_short(int(buf))
            #----------------------------------------
            # Data file settings
            #----------------------------------------
            #-------------------
            # For the single channel, set the fourth argument to the channel
            #-------------------
            if param.value == 0:
                lret.value = cgen_api.GenSaveDataFile(appid, file_path.value, param, ctypes.c_short(ao_channel.value))
            #-------------------
            # For the multiple channels, set the fourth argument to 0
            #-------------------
            else:
                lret.value = cgen_api.GenSaveDataFile(appid, file_path.value, param, 0)
            #----------------------------------------
            # Get error string
            #----------------------------------------
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenSaveDataFile Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenStartOperation
        #--------------------
        elif buf == "9":
            #----------------------------------------
            # Start the output of the application
            #----------------------------------------
            lret.value = cgen_api.GenStartOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStartOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenGetApplicationStatus
        #--------------------
        elif buf == "10":
            #----------------------------------------
            # Get the operating status
            #----------------------------------------
            lret.value = cgen_api.GenGetApplicationStatus(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenGetApplicationStatus Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # Display the status
            #----------------------------------------
            if status.value == 0:
                status_string = "00H(Stopped)"
            elif status.value == 1:
                status_string = "01H(Running)"
            elif status.value == 2:
                status_string = "02H(Waiting for start trigger)"
            elif status.value == 3:
                status_string = "03H(Running, Waiting for start trigger)"
            else:
                status_string = f"{status.value}"
            print(f"Status = {status_string}\n")
        #--------------------
        # GenStopOperation
        #--------------------
        elif buf == "11":
            #----------------------------------------
            # Stop the output of the application
            #----------------------------------------
            lret.value = cgen_api.GenStopOperation(appid)
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenStopOperation Ret = {lret.value} {error_buf.value.decode('sjis')}\n")
        #--------------------
        # GenCloseApplication
        #--------------------
        elif buf == "12":
            #----------------------------------------
            # Perform application close process
            #----------------------------------------
            lret.value = cgen_api.GenCloseApplication(appid, ctypes.byref(status))
            cgen_api.GenGetErrorString(lret, error_buf)
            print(f"\nGenCloseApplication Ret = {lret.value} {error_buf.value.decode('sjis')}")
            #----------------------------------------
            # Display the status
            #----------------------------------------
            if status.value == 0:
                status_string = "0(Normal completed)"
            elif status.value == 1:
                status_string = "1(C-WaveformGenerator completed error)"
            else:
                status_string = f"{status.value}"
            print(f"Status = {status_string}\n")
        #--------------------
        # Quit
        #--------------------
        elif buf == "q":
            break
        #--------------------
        # Out-of-range command
        #--------------------
        else:
            print("\nThe number is out of range.\nPlease try again.\n")
            continue
    #----------------------------------------
    # Terminate application
    #----------------------------------------
    sys.exit()


#----------------------------------------
# Call main function
#----------------------------------------
if __name__ == "__main__":
    main()
