using System.Collections;
using System.Collections.ObjectModel;
using AsReader251GMAUIiOSDemo.Platforms.iOS;
using static AsReader251GMAUIiOSDemo.Platforms.iOS.AsReader251GDefine;

namespace AsReader251GMAUIiOSDemo;

public partial class RFIDInventoryPage : ContentPage
{
    private AsReader251GManager formManager;
    private AsReader251GDelegate asReader251GDelegate;
    ArrayList powerGainArray;
    int count;
    int powerGain;
    private AsReader251G_CommandType actionState;
    private ObservableCollection<ItemData> RFIDItems = new ObservableCollection<ItemData>();
    public ObservableCollection<ItemData> ItemData { get { return RFIDItems; } }
    private Dictionary<string, ItemData> dataDic = new Dictionary<string, ItemData>();
    BaseViewModel vm = new BaseViewModel();

    public RFIDInventoryPage()
    {
        InitializeComponent();
        this.BindingContext = vm;
        Title = "RFID Inventory";
        count = 0;
        powerGain = 5;
        actionState = AsReader251G_CommandType.CommandStop;
        formManager = AsReader251GManager.sharedInstance();
        asReader251GDelegate = AsReader251GDelegate.sharedInstance();
        asReader251GDelegate.ReaderInitialized = (bool connect) =>
        {
            ReaderInitialized(connect);
        };
        asReader251GDelegate.ReadTag = (string tag, float rssi, float phase, float frequency) =>
        {
            ReadTag(tag, rssi, phase, frequency);
        };
        asReader251GDelegate.OnAsReaderTriggerKeyEvent = (bool status) =>
        {
            bool sta = OnAsReaderTriggerKeyEvent(status);
            return sta;
        };
        asReader251GDelegate.ChangedActionState = (AsReader251G_CommandType action, nint resultCode) =>
        {
            ChangedActionState(action);
        };
        asReader251GDelegate.OnAlert = (string error) =>
        {
            OnAlert(error);
        };
        asReader251GDelegate.OnAsReaderLeftModeKeyEvent = (bool status) =>
        {
            bool sta = OnAsReaderLeftModeKeyEvent(status);
            return sta;
        };
        asReader251GDelegate.OnAsReaderRightModeKeyEvent = (bool status) =>
        {
            bool sta = OnAsReaderRightModeKeyEvent(status);
            return sta;
        };
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        RFIDListView.ItemsSource = RFIDItems;
        Task.Run(() =>
        {
            Utility.LoadActivityIndicator(vm, true);
            
        });
        try
        {
            formManager.SetScanMode(AsReaderGunSDK.ScanMode.RFIDScanMode);
        }
        catch (Exception)
        {
        }
        try
        {
            powerGainArray = formManager.GetPowerGainRange();
            Thread.Sleep(500);
            powerGain = formManager.PowerGain;
        }
        catch (Exception)
        {
            powerGain = formManager.GetPowerRangeMax();
        }
        try
        {
            formManager.SetContinuousMode(true);
        }
        catch (Exception)
        {
        }
        MainThread.BeginInvokeOnMainThread(() =>
        {
            RescanTimePicker.Title = (powerGain / 10).ToString() + ".0dB";
            if (powerGainArray != null)
            {
                foreach (string power in powerGainArray)
                {
                    RescanTimePicker.Items.Add(power);
                }
            }
            if (RescanTimePicker.Title == "")
            {
                RescanTimePicker.SelectedIndex = 0;
            }
            else
            {
                RescanTimePicker.SelectedIndex = powerGainArray.IndexOf(RescanTimePicker.Title);
            }
            Task.Run(() =>
            {
                Thread.Sleep(500);
                Utility.LoadActivityIndicator(vm, false);

            });
        });
    }
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        formManager.Stop();
    }
    void StartScanButton_Clicked(object sender, EventArgs e)
    {
        if (actionState == AsReader251G_CommandType.CommandInventory)
        {
            formManager.Stop();
        }
        else if (actionState == AsReader251G_CommandType.CommandStop)
        {
            formManager.Inventory();
        }
    }
    void ClearScanButton_Clicked(object sender, EventArgs e)
    {
        count = 0;
        CountLabel.Text = count.ToString();
        dataDic.Clear();
        RFIDItems.Clear();
    }
    void OnPickerSelectedIndexChanged(object sender, EventArgs e)
    {
        var picker = (Picker)sender;
        int selectedIndex = picker.SelectedIndex;
        if (selectedIndex != -1)
        {
            string powerGain = picker.Items[selectedIndex];
            RescanTimePicker.Title = powerGain;
            selectedIndex = selectedIndex + formManager.GetPowerRangeMin() / 10;
            formManager.PowerGain = selectedIndex * 10;
        }
    }
    private void ReaderInitialized(bool connect)
    {
        if (!connect)
        {
            MainThread.BeginInvokeOnMainThread(() =>
            {
                Navigation.PopAsync();
            });
        }
    }
    private void ReadTag(string tag, float rssi, float phase, float frequency)
    {
        ItemData InventoryDataChanged;
        if (dataDic.ContainsKey(tag))
        {
            InventoryDataChanged = dataDic[tag];
            InventoryDataChanged.Count++;
            dataDic[tag] = InventoryDataChanged;
        }
        else
        {
            int nowCount = dataDic.Count;
            InventoryDataChanged = new ItemData("0", tag, 1);
            dataDic.Add(tag, InventoryDataChanged);
            RFIDItems.Add(InventoryDataChanged);
        }
        count++;
        MainThread.BeginInvokeOnMainThread(() =>
        {
            RFIDListView.ItemsSource = null;
            RFIDListView.ItemsSource = RFIDItems;
            CountLabel.Text = count.ToString();
        });
    }
    private bool OnAsReaderTriggerKeyEvent(bool status)
    {
        if (formManager.GetScanMode() == AsReaderGunSDK.ScanMode.RFIDScanMode)
        {
            if (status)
            {
                formManager.Inventory();
            }
            else
            {
                formManager.Stop();
            }
            return false;
        } else
        {
            return true;
        }
    }
    private void ChangedActionState(AsReader251G_CommandType action)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (action == AsReader251G_CommandType.CommandInventory)
            {
                actionState = AsReader251G_CommandType.CommandInventory;
                StartScanButton.Text = "Stop Scan";
            }
            else if (action == AsReader251G_CommandType.CommandStop)
            {
                actionState = AsReader251G_CommandType.CommandStop;
                StartScanButton.Text = "Inventory";
            }
        });
    }
    private void OnAlert(string error)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            DisplayAlert("Alert", error, "OK");
        });
    }
    public bool OnAsReaderLeftModeKeyEvent(bool status)
    {
        if (formManager.GetReaderIsModule())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    public bool OnAsReaderRightModeKeyEvent(bool status)
    {
        if (formManager.GetReaderIsModule())
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
