using AsReaderBLESDK.IOS;
using AsReaderSDK4.IOS;
using AsReaderSDK4MAUIDemo.Platforms.iOS;
using AsReaderSDK4MAUIDemo.ViewModels;
using CoreBluetooth;
using Foundation;
using System.Collections.ObjectModel;
using UIKit;
using CoreAnimation;
using Drastic.MBProgressHUD;
using System.Runtime.InteropServices;
using Microsoft.Maui.Controls;

namespace AsReaderSDK4MAUIDemo;

public partial class MainPage : ContentPage
{
    private ObservableCollection<DataModel> dataModelList = new ObservableCollection<DataModel>();
    private ObservableCollection<DataModel> DataModel { get { return dataModelList; } }
    private AsReaderDockManager asReaderDockManager;
    private AsReaderDockManagerDelegate asReaderDockManagerDelegate;
    private SelectType selectType;
    private SelectSegment selectSegment;
    private NSMutableArray arrDeviceList;

    public MainPage()
    {
        InitializeComponent();
        Title = "Unknown Device";
        Settings.Text = "";
        Settings.IsEnabled = false;
        setTypeStatus(false);
        StartScanButton.IsVisible = false;
        ClearButton.IsVisible = false;
        StopButton.IsVisible = false;
        BLEScanButton.IsVisible = false;
        arrDeviceList = new NSMutableArray();
        dataModelList = new ObservableCollection<DataModel>();
        ListView.ItemsSource = dataModelList;
        asReaderDockManager = AsReaderDockManager.sharedInstance();
        asReaderDockManagerDelegate = AsReaderDockManagerDelegate.sharedInstance();
        selectType = SelectType.SelectTypeUSB;
        selectSegment = SelectSegment.SelectSegmentBarcode;
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        asReaderDockManagerDelegate.Plugged = (plug) =>
        {
            Plugged(plug);
        };
        asReaderDockManagerDelegate.ReaderConnected = (status) =>
        {
            ReaderConnected(status);
        };
        asReaderDockManagerDelegate.BatteryReceived = (battery) =>
        {
            BatteryReceived(battery);
        };
        asReaderDockManagerDelegate.ErrorReceived = (errorCode) =>
        {
            ErrorReceived(errorCode);
        };
        asReaderDockManagerDelegate.ResponsePowerOnOff = (isOn, isHWModeChange) =>
        {
            ResponsePowerOnOff(isOn, isHWModeChange);
        };
        asReaderDockManagerDelegate.PushedTriggerButton = () =>
        {
            PushedTriggerButton();
        };
        asReaderDockManagerDelegate.ReleasedTriggerButton = () =>
        {
            ReleasedTriggerButton();
        };
        asReaderDockManagerDelegate.CheckTriggerStatus = (strStatus) =>
        {
            CheckTriggerStatus(strStatus);
        };
        asReaderDockManagerDelegate.ReceivedScanData = (readData) =>
        {
            ReceivedScanData(readData);
        };
        asReaderDockManagerDelegate.PcEpcRssiReceived = (pcEpc, rssi) =>
        {
            PcEpcRssiReceived(pcEpc, rssi);
        };
        asReaderDockManagerDelegate.ScanningBleDeive = (device) =>
        {
            ScanningBleDeive(device);
        };
        asReaderDockManagerDelegate.ScanBleStatus = (status) =>
        {
            ScanBleStatus(status);
        };
        if (!asReaderDockManager.isOpened())
        {
            Unplug();
        }
    }
    protected override void OnDisappearing()
    {
        base.OnDisappearing();
        asReaderDockManager.stop(selectSegment);
        asReaderDockManagerDelegate.Plugged = null;
        asReaderDockManagerDelegate.ReaderConnected = null;
        asReaderDockManagerDelegate.BatteryReceived = null;
        asReaderDockManagerDelegate.ErrorReceived = null;
        asReaderDockManagerDelegate.ResponsePowerOnOff = null;
        asReaderDockManagerDelegate.PushedTriggerButton = null;
        asReaderDockManagerDelegate.ReleasedTriggerButton = null;
        asReaderDockManagerDelegate.CheckTriggerStatus = null;
        asReaderDockManagerDelegate.ReceivedScanData = null;
        asReaderDockManagerDelegate.PcEpcRssiReceived = null;
        asReaderDockManagerDelegate.ScanningBleDeive = null;
        asReaderDockManagerDelegate.ScanBleStatus = null;
    }
    private void setTypeStatus(bool isOn)
    {
        ConnectSwitch.IsVisible = isOn;
        ConnectSwitch.IsEnabled = isOn;
        setBarcodeButton(isOn);
        setRfidButton(isOn);
        setNfcButton(isOn);
        setDualButton(isOn);
        setLfButton(isOn);
    }
    private async void OnSettingsClicked(object sender, EventArgs e)
    {
        await Navigation.PushAsync(new SettingPage());
    }
    private void OnBLEScanClicked(object sender, EventArgs e)
    {
        if (arrDeviceList == null)
        {
            arrDeviceList = new NSMutableArray();
        }
        arrDeviceList.RemoveAllObjects();
        if (!asReaderDockManager.isOpened())
        {
            asReaderDockManager.startBleScan();
        }
        else
        {
            asReaderDockManager.disConnectBle();
        }
    }
    [Obsolete]
    private void OnUSBClicked(object sender, EventArgs e)
    {
        USBButton.IsVisible = false;
        BLEButton.IsVisible = false;
        USBButton.TextColor = Colors.Blue;
        USBButton.BorderColor = Colors.Blue;
        BLEButton.TextColor = Colors.Black;
        BLEButton.BorderColor = Colors.Black;
        Device.StartTimer(TimeSpan.FromSeconds(5.0), showSegment);
        BLEScanButton.IsVisible = false;
        selectType = SelectType.SelectTypeUSB;
        asReaderDockManager.setConnectionType(selectType);
    }
    [Obsolete]
    private void OnBLEClicked(object sender, EventArgs e)
    {
        USBButton.IsVisible = false;
        BLEButton.IsVisible = false;
        USBButton.TextColor = Colors.Black;
        USBButton.BorderColor = Colors.Black;
        BLEButton.TextColor = Colors.Blue;
        BLEButton.BorderColor = Colors.Blue;
        Device.StartTimer(TimeSpan.FromSeconds(5.0), showSegment);
        BLEScanButton.IsVisible = true;
        selectType = SelectType.SelectTypeBLE;
        asReaderDockManager.setConnectionType(selectType);
    }
    private bool showSegment()
    {
        USBButton.IsVisible = true;
        BLEButton.IsVisible = true;
        return false;
    }
    private void OnBarcodeClicked(object sender, EventArgs e)
    {
        if (selectSegment == SelectSegment.SelectSegmentBarcode)
        {
            return;
        }
        setBarcodeButtonColor();
        selectSegment = SelectSegment.SelectSegmentBarcode;
        Preferences.Set("selectType", "0");
        ConnectSwitch.IsEnabled = true;
        ConnectSwitch.IsToggled = false;
    }
    private void OnRfidClicked(object sender, EventArgs e)
    {
        if (selectSegment == SelectSegment.SelectSegmentRFID)
        {
            return;
        }
        setRfidButtonColor();
        selectSegment = SelectSegment.SelectSegmentRFID;
        Preferences.Set("selectType", "1");
        ConnectSwitch.IsEnabled = true;
        ConnectSwitch.IsToggled = false;
    }
    private void OnNfcClicked(object sender, EventArgs e)
    {
        if (selectSegment == SelectSegment.SelectSegmentNFC)
        {
            return;
        }
        setNfcButtonColor();
        selectSegment = SelectSegment.SelectSegmentNFC;
        Preferences.Set("selectType", "2");
        ConnectSwitch.IsEnabled = true;
        ConnectSwitch.IsToggled = false;
    }
    private void OnDualClicked(object sender, EventArgs e)
    {
        if (selectSegment == SelectSegment.SelectSegmentDual)
        {
            return;
        }
        setDualButtonColor();
        selectSegment = SelectSegment.SelectSegmentDual;
        Preferences.Set("selectType", "3");
        ConnectSwitch.IsEnabled = true;
        ConnectSwitch.IsToggled = false;
    }
    private void OnLFClicked(object sender, EventArgs e)
    {
        if (selectSegment == SelectSegment.SelectSegmentRFIDLF)
        {
            return;
        }
        setLfButtonColor();
        selectSegment = SelectSegment.SelectSegmentRFIDLF;
        Preferences.Set("selectType", "4");
        ConnectSwitch.IsEnabled = true;
        ConnectSwitch.IsToggled = false;
    }
    private void OnBarcodeClicked()
    {
        setBarcodeButtonColor();
        selectSegment = SelectSegment.SelectSegmentBarcode;
        Preferences.Set("selectType", "0");
    }
    private void OnRfidClicked()
    {
        setRfidButtonColor();
        selectSegment = SelectSegment.SelectSegmentRFID;
        Preferences.Set("selectType", "1");
    }
    private void OnNfcClicked()
    {
        setNfcButtonColor();
        selectSegment = SelectSegment.SelectSegmentNFC;
        Preferences.Set("selectType", "2");
    }
    private void OnDualClicked()
    {
        setDualButtonColor();
        selectSegment = SelectSegment.SelectSegmentDual;
        Preferences.Set("selectType", "3");
    }
    private void OnLFClicked()
    {
        setLfButtonColor();
        selectSegment = SelectSegment.SelectSegmentRFIDLF;
        Preferences.Set("selectType", "4");
    }
    private void OnScanClicked(object sender, EventArgs e)
    {
        asReaderDockManager.read(selectSegment);
    }
    private void OnClearClicked(object sender, EventArgs e)
    {
        dataModelList = new ObservableCollection<DataModel>();
        ListView.ItemsSource = dataModelList;
        TagLabel.Text = dataModelList.Count.ToString() + " tags";
    }
    private void OnStopClicked(object sender, EventArgs e)
    {
        asReaderDockManager.stop(selectSegment);
    }
    [Obsolete]
    void OnToggledConnect(object sender, ToggledEventArgs e)
    {
        showGlobalProgressHUDWithTitle("");
        Device.StartTimer(TimeSpan.FromSeconds(3.0), dismiss);
        asReaderDockManager.setPower(e.Value, selectSegment);
    }
    private async void OnListViewItemTapped(object sender, ItemTappedEventArgs e)
    {
        var selectedItem = e.Item as DataModel;
        if (selectedItem == null) return;
        ((ListView)sender).SelectedItem = null;
        await Navigation.PushAsync(new DetailPage(selectedItem.Epc));
    }
    private bool dismiss()
    {
        dismissGlobalHUD();
        return false;
    }
    private void Plugged(bool plug)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (plug)
            {
                if (asReaderDockManager.isPowerOn())
                {
                    StatusLabel.Text = "Connected";
                    StatusLabel.TextColor = Colors.Blue;
                }
                else
                {
                    StatusLabel.Text = "Plugged";
                    StatusLabel.TextColor = Colors.Red;
                }
                ConnectSwitch.IsVisible = true;
                ConnectSwitch.IsEnabled = true;
                Title = asReaderDockManager.deviceName();
                if (asReaderDockManager.supportTypeBarcode())
                {
                    setBarcodeButton(true);
                }
                if (asReaderDockManager.supportTypeRFID())
                {
                    setRfidButton(true);
                }
                if (asReaderDockManager.supportTypeNFC())
                {
                    setNfcButton(true);
                }
                if (asReaderDockManager.supportTypeDual())
                {
                    setDualButton(true);
                }
                if (asReaderDockManager.supportTypeRFIDLF())
                {
                    setLfButton(true);
                }
                string selectType = Preferences.Get("selectType", "");
                if (selectType == "0")
                {
                    if (asReaderDockManager.supportTypeBarcode())
                    {
                        OnBarcodeClicked();
                    }
                    else
                    {
                        setSupportSelegemntType();
                    }
                } else if (selectType == "1")
                {
                    if (asReaderDockManager.supportTypeRFID())
                    {
                        OnRfidClicked();
                    } else {
                        setSupportSelegemntType();
                    }
                }
                else if (selectType == "2")
                {
                    if (asReaderDockManager.supportTypeNFC())
                    {
                        OnNfcClicked();
                    } else
                    {
                        setSupportSelegemntType();
                    }
                } else if (selectType == "3")
                {
                    if (asReaderDockManager.supportTypeDual())
                    {
                        OnDualClicked();
                    }
                    else
                    {
                        setSupportSelegemntType();
                    }
                } else if (selectType == "4")
                {
                    if (asReaderDockManager.supportTypeRFIDLF())
                    {
                        OnLFClicked();
                    }
                    else
                    {
                        setSupportSelegemntType();
                    }
                }
                ConnectSwitch.IsToggled = true;
            }
            else
            {
                Unplug();
            }
        });
    }
    private void setSupportSelegemntType()
    {
        SupportType support = asReaderDockManager.getSupportType();
        switch (support)
        {
            case SupportType.Barcode:
                OnBarcodeClicked();
                break;
            case SupportType.Rfid:
                OnRfidClicked();
                break;
            case SupportType.Nfc:
                OnNfcClicked();
                break;
            case SupportType.Dual:
                OnDualClicked();
                break;
            case SupportType.Rfidlf:
                OnLFClicked();
                break;
        }
    }
    private void disConnectedState()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            StatusLabel.Text = "Disconnected";
            StatusLabel.TextColor = Colors.Red;
            ConnectSwitch.IsVisible = true;
            StartScanButton.IsVisible = false;
            ClearButton.IsVisible = false;
            StopButton.IsVisible = false;
            Settings.Text = "";
            Settings.IsEnabled = false;
        });
    }
    private void ReaderConnected(int status)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (status == 0xff)
            {
                StatusLabel.Text = "Connected";
                StatusLabel.TextColor = Colors.Blue;
                StartScanButton.IsVisible = true;
                ClearButton.IsVisible = true;
                StopButton.IsVisible = true;
                ConnectSwitch.IsVisible = true;
                Settings.IsEnabled = true;
                Settings.Text = "More";
                asReaderDockManager.setTriggerMode(true);
                if (asReaderDockManager.getIs025S() || asReaderDockManager.getIsM30S())
                {
                    ConnectSwitch.IsEnabled = false;
                    int battery = asReaderDockManager.getBattery();
                    BatteryReceived(battery);
                }
                if (asReaderDockManager.getIsM30S())
                {
                    asReaderDockManager.setM30SContinuousMode(true);
                }
            }
            else
            {
                disConnectedState();
            }
            dismissGlobalHUD();
        });
    }
    private void BatteryReceived(int battery)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            int nVal = 0;
            if (battery > 95)
            {
                nVal = 4;
            }
            else if (battery > 70)
            {
                nVal = 3;
            }
            else if (battery > 45)
            {
                nVal = 2;
            }
            else if (battery > 20)
            {
                nVal = 1;
            }
            else
            {
                nVal = 0;
            }
            UIDevice currentDevice = UIDevice.CurrentDevice;
            UIDeviceBatteryState currentState = currentDevice.BatteryState;
            bool mbIsCahrging = false;
            if ((currentState == UIDeviceBatteryState.Charging) || (currentState == UIDeviceBatteryState.Full))
            {
                mbIsCahrging = true;
            }
            else
            {
                mbIsCahrging = false;
            }
            string imageName;
            if (mbIsCahrging)
            {
                imageName = "bat_charge_" + nVal + ".png";
            }
            else
            {
                imageName = "bat_normal_" + nVal + ".png";
            }
            BatteryImage.Source = imageName;
        });
    }
    private void ErrorReceived(NSData errorCode)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            byte[] b = errorCode.ToArray();
            Marshal.Copy(errorCode.Bytes, b, 0, Convert.ToInt32(errorCode.Length));
            if ((b[0] == 0x01) && (b[1] == 0x01) && (b[2] == 0xE9))
            {
                DisplayAlert("Err", "Error (Mode change)", "OK");
            }
        });
    }
    private void ResponsePowerOnOff(bool isOn, bool isHWModeChange)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (isHWModeChange)
            {
                if (asReaderDockManager.currentReaderMode() == ReaderMode.Unknown)
                {
                    setBarcodeButton(false);
                    setRfidButton(false);
                    setNfcButton(false);
                    setDualButton(false);
                    setLfButton(false);
                }
                else if (asReaderDockManager.currentReaderMode() == ReaderMode.Barcode)
                {
                    setBarcodeButtonColor();
                    selectSegment = SelectSegment.SelectSegmentBarcode;
                    Preferences.Set("selectType", "0");
                }
                else if (asReaderDockManager.currentReaderMode() == ReaderMode.Rfid)
                {
                    setRfidButtonColor();
                    selectSegment = SelectSegment.SelectSegmentRFID;
                    Preferences.Set("selectType", "1");
                }
                else if (asReaderDockManager.currentReaderMode() == ReaderMode.Nfc)
                {
                    setNfcButtonColor();
                    selectSegment = SelectSegment.SelectSegmentNFC;
                    Preferences.Set("selectType", "2");
                }
                else if (asReaderDockManager.currentReaderMode() == ReaderMode.Dual)
                {
                    setDualButtonColor();
                    selectSegment = SelectSegment.SelectSegmentDual;
                    Preferences.Set("selectType", "3");
                }
                else if (asReaderDockManager.currentReaderMode() == ReaderMode.Rfidlf)
                {
                    setLfButtonColor();
                    selectSegment = SelectSegment.SelectSegmentRFIDLF;
                    Preferences.Set("selectType", "4");
                }
            }
        });
    }
    private void PushedTriggerButton()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Title = "Custom TriggerDown";
        });
    }
    private void ReleasedTriggerButton()
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Title = "Custom TriggerDownUp";
        });
    }
    private void CheckTriggerStatus(string strStatus)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            Title = strStatus;
        });
    }
    private void ReceivedScanData(NSData readData)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            string tag = "";
            byte[] ptr = new byte[readData.Length];
            Marshal.Copy(readData.Bytes, ptr, 0, Convert.ToInt32(readData.Length));
            switch (asReaderDockManager.currentReaderMode())
            {
                case ReaderMode.Barcode:
                    NSString str = new NSString();
                    try
                    {
                        str = new NSString(readData, NSStringEncoding.ShiftJIS);
                    }
                    catch
                    {
                        try
                        {
                            str = new NSString(readData, NSStringEncoding.UTF8);
                        }
                        catch
                        {
                            try
                            {
                                str = new NSString(readData, NSStringEncoding.ASCIIStringEncoding);
                            }
                            catch
                            {
                                str = new NSString("Encoding Error");
                            }
                        }
                    }
                    if (str != null) tag = str.ToString();
                    break;
                case ReaderMode.Nfc:
                    int df_NFCDATA_HEADER_SIZE = 4;
                    int df_NFCDATA_FOOTER_SIZE = 3;
                    int nNFCDataLen = ptr[3];
                    int nTotalSize = nNFCDataLen + df_NFCDATA_HEADER_SIZE + df_NFCDATA_FOOTER_SIZE;
                    Byte btSum = 0x00;
                    for (int i = 0; i < nNFCDataLen + df_NFCDATA_HEADER_SIZE + 1; i++) btSum = (Byte)(btSum + ptr[i]);
                    if (nTotalSize != (int)readData.Length) tag += "Data Size Err";
                    else if (btSum != ptr[df_NFCDATA_HEADER_SIZE + nNFCDataLen + 1]) tag += "Check Sum Err";
                    else if ((ptr[0] == 0x02) && (ptr[df_NFCDATA_HEADER_SIZE + nNFCDataLen] == 0x03) && (nTotalSize == (int)readData.Length))
                    {
                        for (int i = 0; i < nNFCDataLen; i++) tag += (ptr[i + 4] & 0xFF).ToString("X2");
                    }
                    else tag += "Data Format Err";
                    break;
                case ReaderMode.Rfid:
                    for (int i = 0; i < (int)readData.Length; i++) tag += (ptr[i] & 0xFF).ToString("X2");
                    break;
                case ReaderMode.Rfidlf:
                    for (int i = 0; i < (int)readData.Length; i++) tag += (ptr[i] & 0xFF).ToString("X2");
                    break;
                case ReaderMode.Dual:
                    
                    if (asReaderDockManager.receiveDataType() == ReaderMode.Barcode)
                    {
                        NSString strin = new NSString();
                        try { strin = new NSString(readData, NSStringEncoding.ShiftJIS); }
                        catch { strin = new NSString(readData, NSStringEncoding.UTF8); }
                        if (strin != null) tag = strin.ToString();
                    }
                    else if (asReaderDockManager.receiveDataType() == ReaderMode.Rfid)
                    {
                        for (int i = 0; i < (int)readData.Length; i++) tag += (ptr[i] & 0xFF).ToString("X2");
                    }
                    break;
                default:
                    tag += "Not Found Device Type";
                    break;

            }
            if (tag.Length > 0)
            {
                addScanDataFiltering(new NSString(tag), readData, 0);
            }
        });
    }
    private void PcEpcRssiReceived(NSData pcEpc, int rssi)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            string tag = "";
            byte[] ptr = new byte[pcEpc.Length];
            Marshal.Copy(pcEpc.Bytes, ptr, 0, Convert.ToInt32(pcEpc.Length));
            for (int i = 0; i < (int)pcEpc.Length; i++) tag += (ptr[i] & 0xFF).ToString("X2");
            addScanDataFiltering(new NSString(tag), pcEpc, rssi);
        });
    }
    private void addScanDataFiltering(NSString strScanRead, NSData dataRaw, int rssi)
    {
        if (strScanRead == "NR")
        {
            bool isNew = true;
            for (int i = 0; i < dataModelList.Count; i++)
            {
                DataModel dataModel = dataModelList[i];
                if (dataModel.Epc == strScanRead)
                {
                    isNew = false;
                    int count = int.Parse(dataModel.Count) + 1;
                    dataModelList.RemoveAt(i);
                    dataModelList.Insert(i, new DataModel("icon_barcode.png", "", "NR", count.ToString()));
                    break;
                }
            }
            if (isNew)
            {
                dataModelList.Insert(0, new DataModel("icon_barcode.png", "", "NR", "1"));
            }
            return;
        }

        bool isNewData = true;
        for (int i = 0; i < dataModelList.Count; i++)
        {
            DataModel dataModel = dataModelList[i];
            if (dataModel.Epc == strScanRead || dataModel.Epc == RainTagHelper.getEPC(dataRaw))
            {
                isNewData = false;
                int count = int.Parse(dataModel.Count) + 1;
                dataModelList.RemoveAt(i);
                string type = "";
                string pc = "";
                string epc = "";
                switch (asReaderDockManager.receiveDataType())
                {
                    case ReaderMode.Barcode:
                        type = "icon_barcode.png";
                        pc = "";
                        epc = strScanRead;
                        break;
                    case ReaderMode.Nfc:
                        type = "icon_nfc.png";
                        pc = "";
                        epc = strScanRead;
                        break;
                    case ReaderMode.Rfid:
                        type = "icon_rfid.png";
                        pc = RainTagHelper.getPC(dataRaw);
                        epc = RainTagHelper.getEPC(dataRaw);
                        break;
                    case ReaderMode.Rfidlf:
                        type = "icon_rfid.png";
                        NSDictionary getDic = LFTagParser.SharedInstance().ParseDataByProtocolType(dataRaw, ProtocolTypeLF.ProtocolTypeLF_FDBX);
                        string natinalCode = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_NationalCode).ToString();
                        string countryCode = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_CountryCode).ToString();
                        string statusFlag = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_StatusFlag).ToString();
                        string animalIndicator = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_AnimalIndicator).ToString();
                        string reserved = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_Reserved).ToString();
                        pc = natinalCode + countryCode + statusFlag + animalIndicator + reserved;
                        epc = strScanRead;
                        break;
                }
                dataModelList.Insert(i, new DataModel(type, pc, epc, count.ToString()));
                break;
            }
        }
        if (isNewData)
        {
            string type = "";
            string pc = "";
            string epc = "";
            switch (asReaderDockManager.receiveDataType())
            {
                case ReaderMode.Barcode:
                    type = "icon_barcode.png";
                    pc = "";
                    epc = strScanRead;
                    break;
                case ReaderMode.Nfc:
                    type = "icon_nfc.png";
                    pc = "";
                    epc = strScanRead;
                    break;
                case ReaderMode.Rfid:
                    type = "icon_rfid.png";
                    pc = RainTagHelper.getPC(dataRaw);
                    epc = RainTagHelper.getEPC(dataRaw);
                    break;
                case ReaderMode.Rfidlf:
                    type = "icon_rfid.png";
                    NSDictionary getDic = LFTagParser.SharedInstance().ParseDataByProtocolType(dataRaw, ProtocolTypeLF.ProtocolTypeLF_FDBX);
                    string natinalCode = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_NationalCode).ToString();
                    string countryCode = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_CountryCode).ToString();
                    string statusFlag = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_StatusFlag).ToString();
                    string animalIndicator = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_AnimalIndicator).ToString();
                    string reserved = getDic.ValueForKey(AsReaderDockManager.Key_FDBX_Reserved).ToString();
                    pc = natinalCode + countryCode + statusFlag + animalIndicator + reserved;
                    epc = strScanRead;
                    break;
            }
            if (epc.Length > 0) {
                dataModelList.Insert(0, new DataModel(type, pc, epc, "1"));
            }
        }
        TagLabel.Text = dataModelList.Count.ToString() + " tags";
    }
    private void ScanningBleDeive(CBPeripheral device)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            arrDeviceList.Add(device);
        });
    }
    private void ScanBleStatus(BleStatusCodes status)
    {
        MainThread.BeginInvokeOnMainThread(() =>
        {
            if (status == BleStatusCodes.Ning)
            {
                showGlobalProgressHUDWithTitle("Searching for device.");
            }
            if (status == BleStatusCodes.Stop)
            {
                dismissGlobalHUD();
                if (arrDeviceList.Count != 0)
                {
                    showAlert(title: (NSString)"Barcode reader connection", message: (NSString)"Please select a searched device below", bleDevices: arrDeviceList);
                }
                else
                {
                    DisplayAlert("No reader found.", "Check the power of the reader.", "OK");
                }
            }
        });
    }
    private string getEncodingString(NSData pcEpc)
    {
        return EpcConverter.toString(0, pcEpc);
    }
    private async void showAlert(NSString title, NSString message, NSMutableArray bleDevices)
    {
        List<string> list = new List<string>();
        Dictionary<string ,CBPeripheral> dictionary = new Dictionary<string, CBPeripheral>();
        for (int i = 0; i < (int)bleDevices.Count; i++)
        {
            CBPeripheral device = bleDevices.GetItem<CBPeripheral>((nuint)i);
            list.Add(device.Name);
            dictionary.Add(device.Name, device);
        }
        string[] buttons = list.ToArray();
        var action = await DisplayActionSheet(title, "Cancel", message, buttons);
        if (dictionary.ContainsKey(action)) {
            CBPeripheral device = dictionary[action];
            asReaderDockManager.connectBle(device);
        }
    }
    private void showGlobalProgressHUDWithTitle(string title)
    {
        UIWindow window = UIApplication.SharedApplication.KeyWindow;
        MBProgressHUD hud = MBProgressHUD.ShowHUDAddedTo(window, true);
        hud.Label.Text = title;
        hud.Mode = MBProgressHUDMode.Text;
        CATransaction.Commit();
    }
    private void dismissGlobalHUD()
    {
        UIWindow window = UIApplication.SharedApplication.KeyWindow;
        MBProgressHUD.HideHUDForView(window, true);
        CATransaction.Commit();
    }
    private void setBarcodeButton(bool isOn)
    {
        BarcodeButton.IsEnabled = isOn;
        if (isOn)
        {
            BarcodeButton.TextColor = Colors.Black;
            BarcodeButton.BorderColor = Colors.Black;
        }
        else
        {
            BarcodeButton.TextColor = Colors.LightGray;
            BarcodeButton.BorderColor = Colors.LightGray;
        }
    }
    private void setRfidButton(bool isOn)
    {
        RfidButton.IsEnabled = isOn;
        if (isOn)
        {
            RfidButton.TextColor = Colors.Black;
            RfidButton.BorderColor = Colors.Black;
        }
        else
        {
            RfidButton.TextColor = Colors.LightGray;
            RfidButton.BorderColor = Colors.LightGray;
        }
    }
    private void setNfcButton(bool isOn)
    {
        NfcButton.IsEnabled = isOn;
        if (isOn)
        {
            NfcButton.TextColor = Colors.Black;
            NfcButton.BorderColor = Colors.Black;
        }
        else
        {
            NfcButton.TextColor = Colors.LightGray;
            NfcButton.BorderColor = Colors.LightGray;
        }
    }
    private void setDualButton(bool isOn)
    {
        DualButton.IsEnabled = isOn;
        if (isOn)
        {
            DualButton.TextColor = Colors.Black;
            DualButton.BorderColor = Colors.Black;
        }
        else
        {
            DualButton.TextColor = Colors.LightGray;
            DualButton.BorderColor = Colors.LightGray;
        }
    }
    private void setLfButton(bool isOn)
    {
        LfButton.IsEnabled = isOn;
        if (isOn)
        {
            LfButton.TextColor = Colors.Black;
            LfButton.BorderColor = Colors.Black;
        }
        else
        {
            LfButton.TextColor = Colors.LightGray;
            LfButton.BorderColor = Colors.LightGray;
        }
    }
    private void setBarcodeButtonColor()
    {
        if (asReaderDockManager.supportTypeBarcode())
        {
            BarcodeButton.TextColor = Colors.Blue;
            BarcodeButton.BorderColor = Colors.Blue;
        }
        if (asReaderDockManager.supportTypeRFID())
        {
            RfidButton.TextColor = Colors.Black;
            RfidButton.BorderColor = Colors.Black;
        };
        if (asReaderDockManager.supportTypeNFC())
        {
            NfcButton.TextColor = Colors.Black;
            NfcButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeDual())
        {
            DualButton.TextColor = Colors.Black;
            DualButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFIDLF())
        {
            LfButton.TextColor = Colors.Black;
            LfButton.BorderColor = Colors.Black;
        }
    }
    private void setRfidButtonColor()
    {
        if (asReaderDockManager.supportTypeBarcode())
        {
            BarcodeButton.TextColor = Colors.Black;
            BarcodeButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFID())
        {
            RfidButton.TextColor = Colors.Blue;
            RfidButton.BorderColor = Colors.Blue;
        };
        if (asReaderDockManager.supportTypeNFC())
        {
            NfcButton.TextColor = Colors.Black;
            NfcButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeDual())
        {
            DualButton.TextColor = Colors.Black;
            DualButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFIDLF())
        {
            LfButton.TextColor = Colors.Black;
            LfButton.BorderColor = Colors.Black;
        }
    }
    private void setNfcButtonColor()
    {
        if (asReaderDockManager.supportTypeBarcode())
        {
            BarcodeButton.TextColor = Colors.Black;
            BarcodeButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFID())
        {
            RfidButton.TextColor = Colors.Black;
            RfidButton.BorderColor = Colors.Black;
        };
        if (asReaderDockManager.supportTypeNFC())
        {
            NfcButton.TextColor = Colors.Blue;
            NfcButton.BorderColor = Colors.Blue;
        }
        if (asReaderDockManager.supportTypeDual())
        {
            DualButton.TextColor = Colors.Black;
            DualButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFIDLF())
        {
            LfButton.TextColor = Colors.Black;
            LfButton.BorderColor = Colors.Black;
        }
    }
    private void setDualButtonColor()
    {
        if (asReaderDockManager.supportTypeBarcode())
        {
            BarcodeButton.TextColor = Colors.Black;
            BarcodeButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFID())
        {
            RfidButton.TextColor = Colors.Black;
            RfidButton.BorderColor = Colors.Black;
        };
        if (asReaderDockManager.supportTypeNFC())
        {
            NfcButton.TextColor = Colors.Black;
            NfcButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeDual())
        {
            DualButton.TextColor = Colors.Blue;
            DualButton.BorderColor = Colors.Blue;
        }
        if (asReaderDockManager.supportTypeRFIDLF())
        {
            LfButton.TextColor = Colors.Black;
            LfButton.BorderColor = Colors.Black;
        }
    }
    private void setLfButtonColor()
    {
        if (asReaderDockManager.supportTypeBarcode())
        {
            BarcodeButton.TextColor = Colors.Black;
            BarcodeButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFID())
        {
            RfidButton.TextColor = Colors.Black;
            RfidButton.BorderColor = Colors.Black;
        };
        if (asReaderDockManager.supportTypeNFC())
        {
            NfcButton.TextColor = Colors.Black;
            NfcButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeDual())
        {
            DualButton.TextColor = Colors.Black;
            DualButton.BorderColor = Colors.Black;
        }
        if (asReaderDockManager.supportTypeRFIDLF())
        {
            LfButton.TextColor = Colors.Blue;
            LfButton.BorderColor = Colors.Blue;
        }
    }
    private void Unplug()
    {
        BatteryImage.Source = "battery.png";
        disConnectedState();
        StatusLabel.Text = "UnPlugged";
        setTypeStatus(false);
        ConnectSwitch.IsToggled = false;
        Title = "Unknown Device";
        selectSegment = SelectSegment.SelectSegmentBarcode;
        selectType = SelectType.SelectTypeUSB;
    }
}


