﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.IO;
using CLoggerCs;

namespace ApiBasicLogger
{
    public partial class ApiBasicLogger : Form
    {
        //----------------------------------------
        // Create a CLogger class instance
        //----------------------------------------
        CLogger logger = new CLogger();

        //----------------------------------------
        // Declaration of global variables
        //----------------------------------------
        public short                g_appid;                                // ID for application access
        public GCHandle             gCh;                                    // GCHandle for the callback routine
        public PLOGGEREVENTCALLBACK pdelegate_func;                         // Event notification Delegate
        public IntPtr               pfunc;                                  // IntPtr for the callback routine
        public ulong                g_samplingdata;                         // Sampling data number
        public string               g_file_name;                            // Sampling data output file name
        public ushort               SequenceNum;		                    // Sequence number

        public ApiBasicLogger()
        {
            InitializeComponent();
        }

        //================================================================================
        // Initial Settings
        //================================================================================
        unsafe private void Form1_Load(object sender, EventArgs e)
        {
            //----------------------------------------
            // Update the initial display of device name
            //----------------------------------------
            textBox_DeviceName.Text = "AIO000";
            //----------------------------------------
            // Create the combobox for screen size
            //----------------------------------------
            comboBox_WindowSize.Items.Add("Minimize");
            comboBox_WindowSize.Items.Add("Normal");
            comboBox_WindowSize.Items.Add("Maximize");
            //----------------------------------------
            // Change the selection of screen size combobox to Minimize
            //----------------------------------------
            comboBox_WindowSize.SelectedIndex = (int)CLoggerConst.LOGGER_PARAM_WINDOW_OFF;
            //----------------------------------------
            // Initializing global variables
            //----------------------------------------
            g_appid = 0;
            g_file_name = "SamplingData.csv";
            g_samplingdata = 1;
            SequenceNum = 1;
            //----------------------------------------
            // Initialize the delegate for event notification
            //----------------------------------------
            pdelegate_func = new PLOGGEREVENTCALLBACK(CallBackProc);
            //----------------------------------------
            // Sets the delegate to never be released
            //----------------------------------------
            if (gCh.IsAllocated == false)
            {
                gCh = GCHandle.Alloc(pdelegate_func);
            }
            return;
        }

        //================================================================================
        // It is the process when the LoggerOpenApplication button is clicked
        // Launch the app and enable access
        //================================================================================
        private void button_LoggerOpenApplication_Click(object sender, EventArgs e)
        {
            string  device_name;     // Device name
            ushort  openmode;        // Screen size
            int     ret;             // For return code
            string  error_string;    // Error code string

            //----------------------------------------
            // Get device name from textbox
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // Get screen size from combobox
            //----------------------------------------
            openmode = (ushort)comboBox_WindowSize.SelectedIndex;
            //----------------------------------------
            // Initialize the application
            //----------------------------------------
            ret = logger.OpenApplication(device_name, out g_appid, openmode);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerOpenApplication = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // It is the process when the LoggerSetDeviceName button is clicked
        // Set the device name
        //================================================================================
        private void button_LoggerSetDeviceName_Click(object sender, EventArgs e)
        {
            string  device_name;     // Device name
            int     ret;             // For return code
            string  error_string;    // Error code string

            //----------------------------------------
            // Get device name from textbox
            //----------------------------------------
            device_name = textBox_DeviceName.Text;
            //----------------------------------------
            // Set the device name
            //----------------------------------------
            ret = logger.SetDeviceName(g_appid, device_name);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerSetDeviceName = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // It is the process when the ...button is clicked (settings file)
        // Displays a dialog for selecting a configuration file
        //================================================================================
        private void button_SelectImportSettingFile_Click(object sender, EventArgs e)
        {
            //----------------------------------------
            // Do Not check if the file name exists
            //----------------------------------------
            openFileDialog1.CheckFileExists = false;
            //----------------------------------------
            // If the Then file path exists, Set the file path To the initial path In the dialog.
            //----------------------------------------
            if (textBox_SelectImportSettingFile.Text.Length > 0)
            {
                openFileDialog1.InitialDirectory    = textBox_SelectImportSettingFile.Text;
                openFileDialog1.FileName            = openFileDialog1.SafeFileName;
            }
            //----------------------------------------
            // If the file path does not exist, set MyDocuments to the initial path in the dialog
            //----------------------------------------
            else
            {
                openFileDialog1.InitialDirectory    = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                openFileDialog1.FileName            = "";
            }
            //----------------------------------------
            // Display the selected path
            //----------------------------------------
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                textBox_SelectImportSettingFile.Text = System.IO.Path.GetFullPath(openFileDialog1.FileName);
            }
            return;
        }

        //================================================================================
        // It is the process when the LoggerImportSettingFile button is clicked
        // Import the settings file
        //================================================================================

        private void button_LoggerImportSettingFile_Click(object sender, EventArgs e)
        {
            string  filepath;        // File path
            int     ret;             // For return code
            string  error_string;    // Error code string
            uint    status;          // For status storage              

            //----------------------------------------
            // Get setting file path from the textbox
            //----------------------------------------
            filepath = textBox_SelectImportSettingFile.Text;
            //----------------------------------------
            // Import the settings file
            //----------------------------------------
            ret = logger.ImportSettingFile(g_appid, filepath, out status);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerImportSettingFile = {0} : {1} \r\nstatus=0x{2:X16}", ret, error_string, status);
            return;
        }

        //================================================================================
        // It is the process when the LoggerSetEventSamplingTimes button is clicked
        // Set the specified sampling count
        //================================================================================
        private void button_LoggerSetEventSamplingTimes_Click(object sender, EventArgs e)
        {
            int     ret;                 // For return code
            string  error_string;        // Error code string
            uint    sampling_times;      // For storing the specified sampling count

            //----------------------------------------
            // Get the specified sampling count from the text box
            //----------------------------------------
            if (uint.TryParse(textBox_SamplingTimes.Text, out sampling_times) == false)
            {
                sampling_times = 1000;
            }
            //----------------------------------------
            // Set the specified sampling count
            //----------------------------------------
            ret = logger.SetEventSamplingTimes(g_appid, sampling_times);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerSetEventSamplingTimes = {0} : {1} ", ret, error_string);
            return;
        }

        //================================================================================
        // It is the process when the LoggerGetEventSamplingTimes button is clicked
        // Get the specified sampling count
        //================================================================================
        private void button_LoggerGetEventSamplingTimes_Click(object sender, EventArgs e)
        {
            string  error_string;         // Error code string
            int     ret;                  // For return code
            uint    sampling_times;       // For storing the specified sampling count

            //----------------------------------------
            // Get the specified sampling count from the text box
            //----------------------------------------
            ret = logger.GetEventSamplingTimes(g_appid, out sampling_times);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetEventSamplingTimes = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // If the specified sampling count acquisition function completes successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update the sampling count
                //--------------------
                textBox_SamplingTimes.Text = sampling_times.ToString();
            }
            return;
        }

        //================================================================================
        // It is the process when the Logging Start button is clicked
        // Start the application input and output
        //================================================================================
        unsafe private void button_LoggerStartOperation_Click(object sender, EventArgs e)
        {

            string  	error_string;    				// Error code string
            int     	ret;             				// For return code
            uint    	status;          				// For status storage
            ushort      InputType;                      // Input method
            ushort[]    ChannelNo = new ushort[256];    // Channel number
            byte[]      ChName = new byte[256*256];     // Channel name
            ushort[]    Range = new ushort[256];        // Range            
            ushort      pre_sequence = 256;             // Sequence number

            //----------------------------------------
            // Close file
            //----------------------------------------
            ret = logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            if (ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGraphWindowOperation = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // Delete file
            //----------------------------------------
            if (File.Exists(g_file_name))
            {
                try
                {
                    File.Delete(g_file_name);
                }
                catch
                {
                    textBox_ReturnNum.Text = string.Format("Data file deletion error");
                    return;
                }
            }
            //----------------------------------------
            // Get the channel settings
            //----------------------------------------
            ret = logger.GetChannelSetting(g_appid, out InputType, ref pre_sequence, ChannelNo, ChName, Range);
            if (ret != 0)
            {
                //----------------------------------------
                // Get the error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display the error code and the message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGetChannelSetting = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // Initialize the number of sampling data
            //----------------------------------------
            g_samplingdata = 1;
            //----------------------------------------
            // Specify the buffer mode (API acquisition mode)
            //----------------------------------------
            ret = logger.SetAcquiredMode(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_MODE_API);
            if (ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerSetAcquiredMode = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // Get a fixed pointer to the event notification delegate
            //----------------------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //----------------------------------------
            // Set the event
            //----------------------------------------
            ret = logger.SetNotifyEvent(g_appid, pfunc, (uint)CLoggerConst.LOGGER_PARAM_EVENT_DATANUM | (uint)CLoggerConst.LOGGER_PARAM_EVENT_END, null);
            if (ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerSetNotifyEvent = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // Put the sequence number into a global variable
            //----------------------------------------
            SequenceNum = pre_sequence;
            //----------------------------------------
            // Start the application input and output
            //----------------------------------------
            ret = logger.StartOperation(g_appid, out status);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerStartOperation = {0} : {1} \r\nstatus = {2}", ret, error_string, status);
            return;
        }

        //================================================================================
        // It is the process when the LoggerGetTotalSamplingCount button is clicked
        // Get the total number of samples
        //================================================================================
        private void button_LoggerGetTotalSamplingCount_Click(object sender, EventArgs e)
        {
            string  error_string;         // Error code string
            int     ret;                  // For return code
            uint   sampling_count = 0;    // For total sampling count storage

            //----------------------------------------
            // Get total sampling count
            //----------------------------------------
            ret = logger.GetTotalSamplingCount(g_appid, out sampling_count);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetTotalSamplingCount = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // If the total sampling count acquisition function completes successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update the toal sampling count
                //--------------------
                textBox_TotalSamplingCount.Text = sampling_count.ToString();
            }
            return;
        }

        //================================================================================
        // It is the process when the LoggerGetStoredSamplingCount button is clicked
        // Get the number of samples
        //================================================================================
        private void button_LoggerGetStoredSamplingCount_Click(object sender, EventArgs e)
        {
            string  error_string;               // Error code string
            int     ret;                        // For return code
            uint    stored_sampling_count = 0;  // For sampling count storage

            //----------------------------------------
            // Get sampling count
            //----------------------------------------
            ret = logger.GetStoredSamplingCount(g_appid, out stored_sampling_count);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // If the specified sampling count acquisition function completes successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Update the sampling count
                //--------------------
                textBox_StoredSamplingCount.Text = stored_sampling_count.ToString();
            }
            return;
        }

        //================================================================================
        // It is the process when the LoggerGetApplicationStatus button is clicked
        // Get the device status
        //================================================================================
        private void button_LoggerGetApplicationStatus_Click(object sender, EventArgs e)
        {
            string  status_string = "";   // Status string
            string  error_string;         // Error code string
            int     ret;                  // For return code
            uint    status;               // For status storage

            //----------------------------------------
            // Get the device status
            //----------------------------------------
            ret = logger.GetApplicationStatus(g_appid, out status);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerGetApplicationStatus = {0} : {1} ", ret, error_string);
            //----------------------------------------
            // If the status acquisition function is completed successfully
            //----------------------------------------
            if (ret == 0)
            {
                //--------------------
                // Get status string
                //--------------------
                switch (status)
                {
                    case (uint)CLoggerConst.LOGGER_STATUS_STOP:
                        status_string = "Stop";
                        break;
                    case (uint)CLoggerConst.LOGGER_STATUS_START_TRG:
                        status_string = "Wait the start trigger";
                        break;
                    case (uint)CLoggerConst.LOGGER_STATUS_BUSY:
                        status_string = "Operating";
                        break;
                    default:
                        status_string = "Unknown status";
                        break;
                }
                //----------------------------------------
                // Display the status
                //----------------------------------------
                textBox_ApplicationStatus.Text = string.Format("{0} ({1})", status, status_string);
            }
            return;
        }

        //================================================================================
        // It is the process when the Logging Stop button is clicked
        // Stop the application input and output
        //================================================================================
        unsafe private void button_LoggerStopOperation_Click(object sender, EventArgs e)
        {
            int     ret;                // For return code
            string  error_string;       // Error code string
            uint sampling_times = 0;    // For storing the specified sampling count
            float[] sampling_data;      // For storing sampling data
            long i;                     // For loop counting
            string text_string = "";    // For updating textbox
            StreamWriter fp;            // File pointer
            long j;                     // For loop counting

            //----------------------------------------
            // Get a fixed pointer to the event notification delegate
            //----------------------------------------
            pfunc = Marshal.GetFunctionPointerForDelegate(pdelegate_func);
            //----------------------------------------
            // Stop the application input and output
            //----------------------------------------
            ret = logger.StopOperation(g_appid);
            if(ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerStopOperation = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // Get the sampling count
            //----------------------------------------
            ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
            if (ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("GetStoredSamplingCount = {0} : {1} ", ret, error_string);
                return;
            }
            //----------------------------------------
            // For storing data for a specified number of samplings
            //----------------------------------------
            try
            {
                sampling_data = new float[sampling_times * SequenceNum];
            }
            catch
            {
                textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage";
                return;
            }
            //----------------------------------------
            // Get sampling data
            //----------------------------------------
            ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
            if (ret != 0)
            {
                //----------------------------------------
                // Get error string
                //----------------------------------------
                logger.GetErrorString(ret, out error_string);
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                //--------------------
                // Free the array used for data storage
                //--------------------
                sampling_data = null;
                return;
            }
            //----------------------------------------
            // Open file
            //----------------------------------------
            try
            {
                fp = File.AppendText(g_file_name);
            }
            catch
            {
                textBox_ReturnNum.Text = "Output Acquired Data File：File.AppendText = file open error.";
                return;
            }
            //--------------------
            // Repeat processing until the specified number of samples is reached
            //--------------------
            for (i = 0; i < sampling_times; i++)
            {
                //--------------------
                // Clear the display string storage variable
                //--------------------
                text_string = "";
                //--------------------
                // Generate a string to display
                //--------------------
                text_string += string.Format("{0,5},  ", (g_samplingdata++));
                //--------------------
                // Add sampling data (Repeat the process for the specified number of channels)
                //--------------------
                for (j = 0; j < SequenceNum - 1; j++)
                {
                    text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                }
                text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                //--------------------
                // Data writing
                //--------------------
                try
                {
                    fp.Write(text_string);
                }
                catch
                {
                    textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error.";
                    fp.Close();
                    //--------------------
                    // Free the array used for data storage
                    //--------------------
                    sampling_data = null;
                    return;
                }
            }
            fp.Close();
            //--------------------
            // Free the array used for data storage
            //--------------------
            sampling_data = null;

            //----------------------------------------
            // Display of collection stop completion message
            //----------------------------------------
            textBox_ReturnNum.Text = "LoggerStopOperation：Successful completion";
            return;
        }

        //================================================================================
        // It is the process when the C-LOGGER Exit button is clicked
        // Stop the app and disable access
        //================================================================================
        private void button_LoggerCloseApplication_Click(object sender, EventArgs e)
        {
            uint    status          = 0;      // For status storage
            int     ret;                      // For return code
            string  error_string;             // Error code string
            string  status_string;            // Status string

            //----------------------------------------
            // Close the file(Considering that C-LOGGER may have exited, do not check the result)
            //----------------------------------------
            logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            //----------------------------------------
            // Stop the application and disable access
            //----------------------------------------
            ret = logger.CloseApplication(g_appid, out status);
            //----------------------------------------
            // Get error string
            //----------------------------------------
            logger.GetErrorString(ret, out error_string);
            if (ret != 0)
            {
                //----------------------------------------
                // Display error code and message
                //----------------------------------------
                textBox_ReturnNum.Text = string.Format("LoggerCloseApplication = {0} : {1}", ret, error_string);
                return;
            }
            //----------------------------------------
            // Get error string
            //----------------------------------------
            switch (status)
            {
                case (uint)CLoggerConst.LOGGER_STATUS_SUCCESS:
                    status_string = "Successful completion";
                    break;
                case (uint)CLoggerConst.LOGGER_STATUS_FAILURE:
                    status_string = "C-LOGGER exit error";
                    break;
                default:
                    status_string = "Unknown status";
                    break;
            }
            //----------------------------------------
            // Display error code and message
            //----------------------------------------
            textBox_ReturnNum.Text = string.Format("LoggerCloseApplication = {0} : {1} \r\nstatus = {2} : {3}", ret, error_string, status, status_string);
            return;
        }

        //================================================================================
        // It is the process when the Close button is clicked
        // Exit the application
        //================================================================================
        private void button_Exit_Click(object sender, EventArgs e)
        {
            uint    status          = 0;      // For status storage

            //----------------------------------------
            // Close the file(Considering that C-LOGGER may have exited, do not check the result)
            //----------------------------------------
            logger.GraphWindowOperation(g_appid, (ushort)CLoggerConst.LOGGER_PARAM_GRAPH_CLOSE, (ushort)CLoggerConst.LOGGER_PARAM_FILE, 0);
            //----------------------------------------
            // Stop the application and disable access
            //----------------------------------------
            logger.CloseApplication(g_appid, out status);
            //----------------------------------------
            // Releasing a GCHandle
            //----------------------------------------
            if (gCh.IsAllocated == true)
            {
                gCh.Free();
            }
            //----------------------------------------
            // Exit the dialog
            //----------------------------------------
            this.Close();
            return;
        }

        //================================================================================
        // Callback routine
        //================================================================================
        unsafe public int CallBackProc(short Id, uint Event, int wParam, int lParam, void* Param)
        {
            int ret;                    // For return code
            uint sampling_times;        // For storing the specified sampling count
            string error_string;        // Error code string
            float[] sampling_data;      // For storing sampling data
            long i;                     // For loop counting
            string text_string = "";    // For updating textbox
            StreamWriter fp;            // File pointer
            long j;                     // For loop counting

            //----------------------------------------
            // Specified Number Storage Event
            //----------------------------------------
            if (Event == (long)CLoggerConst.LOGGER_PARAM_EVENT_DATANUM)
            {
                //----------------------------------------
                // Get the sampling count
                //----------------------------------------
                ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
                if(ret != 0)
                {
                    //----------------------------------------
                    // Get error string
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // Display error code and message
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
                    }));
                    return 0;
                }

                //----------------------------------------
                // For storing data for the specified number of samples
                //----------------------------------------
                try
                {
                    sampling_data = new float[sampling_times * SequenceNum];
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage";
                    }));
                    return 0;
                }
                //----------------------------------------
                // Get sampling data
                //----------------------------------------
                ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
                if (ret != 0)
                {
                    //----------------------------------------
                    // Get error string
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // Display error code and message
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                    }));
                    //--------------------
                    // Free the array used for data storage
                    //--------------------
                    sampling_data = null;
                    return 0;
                }

                //----------------------------------------
                // Open file
                //----------------------------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "Output Acquired Data Files：File.AppendText = file open error.";
                    }));
                    return 0;
                }
                //--------------------
                // Repeat processing until the specified number of samples is reached
                //--------------------
                for (i = 0; i < sampling_times; i++)
                {
                    //--------------------
                    // Clear the display string storage variable
                    //--------------------
                    text_string = "";
                    //--------------------
                    // Generate a string to display
                    //--------------------
                    text_string += string.Format("{0,5},  ", (g_samplingdata++));
                    //--------------------
                    // Add sampling data (Repeat the process for the specified number of channels)
                    //--------------------
                    for (j = 0; j < SequenceNum - 1; j++)
                    {
                        text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                    }
                    text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                    //--------------------
                    // Data writing
                    //--------------------
                    try
                    {
                        fp.Write(text_string);
                    }
                    catch
                    {
                        this.Invoke(new Action(() =>
                        {
                            textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error.";
                        }));
                        fp.Close();
                        //--------------------
                        // Free the array used for data storage
                        //--------------------
                        sampling_data = null;
                        return 0;
                    }
                }
                fp.Close();
                //--------------------
                // Free the array used for data storage
                //--------------------
                sampling_data = null;
            }
            //----------------------------------------
            // Specified Number End Event
            //----------------------------------------
            else if (Event == (long)CLoggerConst.LOGGER_PARAM_EVENT_END)
            {
                //----------------------------------------
                // Get the sampling count
                //----------------------------------------
                ret = logger.GetStoredSamplingCount(g_appid, out sampling_times);
                if(ret != 0)
                {
                    //----------------------------------------
                    // Get error string
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // Display error code and message
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetStoredSamplingCount = {0} : {1} ", ret, error_string);
                    }));
                    return 0;
                }

                //----------------------------------------
                // For storing data for the specified number of samples
                //----------------------------------------
                try
                {
                    sampling_data = new float[sampling_times * SequenceNum];
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "Device operation termination event processing: Failed to allocate array for data storage";
                    }));
                    return 0;
                }
                //----------------------------------------
                // Get sampling data
                //----------------------------------------
                ret = logger.GetSamplingData(g_appid, ref sampling_times, ref sampling_data);
                if (ret != 0)
                {
                    //----------------------------------------
                    // Get error string
                    //----------------------------------------
                    logger.GetErrorString(ret, out error_string);
                    //----------------------------------------
                    // Display error code and message
                    //----------------------------------------
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = string.Format("LoggerGetSamplingData = {0} : {1} ", ret, error_string);
                    }));
                    //--------------------
                    // Free the array used for data storage
                    //--------------------
                    sampling_data = null;
                    return 0;
                }

                //----------------------------------------
                // Open file
                //----------------------------------------
                try
                {
                    fp = File.AppendText(g_file_name);
                }
                catch
                {
                    this.Invoke(new Action(() =>
                    {
                        textBox_ReturnNum.Text = "Output Acquired Data Files：File.AppendText = file open error.";
                    }));
                    return 0;
                }
                //--------------------
                // Repeat processing until the specified number of samples is reached
                //--------------------
                for (i = 0; i < sampling_times; i++)
                {
                    //--------------------
                    // Clear the display string storage variable
                    //--------------------
                    text_string = "";
                    //--------------------
                    // Generate a string to display
                    //--------------------
                    text_string += string.Format("{0,5},  ", (g_samplingdata++));
                    //--------------------
                    // Add sampling data (Repeat the process for the specified number of channels)
                    //--------------------
                    for (j = 0; j < SequenceNum - 1; j++)
                    {
                        text_string += string.Format(" {0,10:F5}, ", sampling_data[i * SequenceNum + j]);
                    }
                    text_string += string.Format(" {0,10:F5}\r\n", sampling_data[i * SequenceNum + j]);
                    //--------------------
                    // Data writing
                    //--------------------
                    try
                    {
                        fp.Write(text_string);
                    }
                    catch
                    {
                        this.Invoke(new Action(() =>
                        {
                            textBox_ReturnNum.Text = "Output Acquired Data Files：fp.Write = file write error.";
                        }));
                        fp.Close();
                        //--------------------
                        // Free the array used for data storage
                        //--------------------
                        sampling_data = null;
                        return 0;
                    }
                }
                fp.Close();
                //--------------------
                // Free the array used for data storage
                //--------------------
                sampling_data = null;
            }
            return 0;
        }
    }
}
