using System.Collections.Generic;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ATK;
using System;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Core;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkID=390556

namespace Zebra_RFID_Mobile
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class PageAccess : Page
    {
        ReaderConnect readerObj;
        BaseReciever basereciverobj;
        List<string> memoryBank = new List<string>();
        List<string> lockPriviliges = new List<string>();
        List<string> lockmemoryBanks = new List<string>();
        byte[] filterEPC;
        static Boolean isStartStopSet = false;
        public PageAccess()
        {
            this.InitializeComponent();
            readerObj = ReaderConnect.getInstance();
            basereciverobj = BaseReciever.getInstance();
            TectBoxTagPatternKill.DataContext = ReaderConfig.selectedTagEPC;
            TextBoxTagPatternLock.DataContext = ReaderConfig.selectedTagEPC;
            TextBoxTagPatternReadWrite.DataContext = ReaderConfig.selectedTagEPC;
            memoryBank.Add("EPC");
            memoryBank.Add("TID");
            memoryBank.Add("USER");
            memoryBank.Add("RESERVED");
            ComboBoxMemoryBankReadWrite.ItemsSource = memoryBank;
            ComboBoxMemoryBankReadWrite.SelectedIndex = 0;
            lockmemoryBanks.Add("EPC");
            lockmemoryBanks.Add("USER");
            lockmemoryBanks.Add("TID");
            lockmemoryBanks.Add("KILL PWD");
            lockmemoryBanks.Add("ACCESS PWD");
            ComboBoxMemoryBankLock.ItemsSource = lockmemoryBanks;            
            ComboBoxMemoryBankLock.SelectedIndex = 0;
            lockPriviliges.Add("Read and Write");
            lockPriviliges.Add("Permanent lock");
            lockPriviliges.Add("Permanent Unlock");
            lockPriviliges.Add("Unlock");
            ComboBoxLockPrivileges.ItemsSource = lockPriviliges;
            ComboBoxLockPrivileges.SelectedIndex = 0;
            TextBoxReadData.DataContext = ReaderConfig.accessTagData;
            TextAccessStatus.DataContext = ReaderConfig.accessTagData;
            BatteryDPO.DataContext = ReaderConfig.batteryDPO;
            ReaderConfig.onAccessScreen = true;
        }

        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ReaderConfig.onAccessScreen = true;
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;
            SystemNavigationManager.GetForCurrentView().BackRequested -= App_BackRequested;
        }

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            resetParams();
            this.Frame.Navigate(typeof(MainPage));
        }
        private void AppBarButtonGoToInventory(object sender, RoutedEventArgs e)
        {
            resetParams();
            this.Frame.Navigate(typeof(PageInventory));
        }

        private void AppBarButtonGoToRapidRead(object sender, RoutedEventArgs e)
        {
            resetParams();
            this.Frame.Navigate(typeof(PageRapidRead));
        }

        private void AppBarButtonGoToAccess(object sender, RoutedEventArgs e)
        {
            resetParams();
            this.Frame.Navigate(typeof(PageAccess));
        }

        private void AppBarButtonGoToLocateTag(object sender, RoutedEventArgs e)
        {
            resetParams();
            this.Frame.Navigate(typeof(PageLocateTag));
        }       

        void App_BackRequested(object sender, BackRequestedEventArgs e)
        {
            resetParams();
            Frame.Navigate(typeof(MainPage));
        }

        private async void ButtonRead_Click(object sender, RoutedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                basereciverobj.showStatus(Command_Read.commandName, "No active connection with reader");
                return;
            }
            if (TextBoxTagPatternReadWrite.Text.Equals(""))
            {
                basereciverobj.showStatus(Command_Read.commandName, "Please fill TAG ID");
                return;
            }
            ReaderConfig.accessTagData.RecievedData = "";
            ReaderConfig.isAccessComplete = false;
            await setStartStopParams();
            if (isStartStopSet)
            {
                if (setAccessCriteria(1))
                {
                    Command_Read readObj = new Command_Read();
                    switch (ComboBoxMemoryBankReadWrite.SelectedIndex + 1)
                    {
                        case 1:
                            readObj.Bank = ENUM_MEMORY_BANK.EPC;
                            break;
                        case 2:
                            readObj.Bank = ENUM_MEMORY_BANK.TID;
                            break;
                        case 3:
                            readObj.Bank = ENUM_MEMORY_BANK.USER;
                            break;
                        case 4:
                            readObj.Bank = ENUM_MEMORY_BANK.RESV;
                            break;
                    }
                    readObj.CriteriaIndex = 1;
                    if (TextBoxReadLenght.Text != "")
                        readObj.Length = Convert.ToInt16(TextBoxReadLenght.Text);
                    if (TextBoxReadOffset.Text != "")
                        readObj.Offset = Convert.ToInt16(TextBoxReadOffset.Text);
                    if (TextBoxReadPassword.Text != "")
                        readObj.Password = TextBoxReadPassword.Text;
                    readerObj.writeData(readObj.ToString());
                    ReaderConfig.accessTagData.RecievedStatus = "Operation Timeout";
                    await basereciverobj.isAccessComplete();
                    FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
                    await Task.Delay(1000);
                    AcessFlyout.Hide();
                }
                else
                    ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            }
            else
                ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            await Task.Delay(1000);
            AcessFlyout.Hide();
        }

        private async void resetParams()
        {
            if (ReaderConfig.isReaderConnected == false || !isStartStopSet)
            {
                ReaderConfig.onAccessScreen = false;
                return;
            }
            ReaderConfig.isStartStopSetComplete = false;
            Command_SetAccessCriteria accessCriteriaFilter = new Command_SetAccessCriteria();
            readerObj.writeData(accessCriteriaFilter.ToString());
            Command_SetStartTrigger setStartTrigger = new Command_SetStartTrigger();
            setStartTrigger = ReaderConfig.startTriggerParams;
            readerObj.writeData(setStartTrigger.ToString());
            Command_SetStopTrigger setStopTrigger = new Command_SetStopTrigger();
            setStopTrigger = ReaderConfig.stopTriggerParams;
            readerObj.writeData(setStopTrigger.ToString());
            await basereciverobj.isStartStopConfigSetCompltete();
            ReaderConfig.onAccessScreen = false;
        }

        private async Task<bool> setStartStopParams()
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                return true;
            }
            ReaderConfig.isStartStopSetComplete = false;
            isStartStopSet = false;
            Command_SetStartTrigger setStartTrigger = new Command_SetStartTrigger();
            setStartTrigger.IgnoreHandHeldTrigger = true;
            setStartTrigger.StartOnHandHeldTrigger = false;
            setStartTrigger.NoRepeat = true;
            setStartTrigger.Repeat = false;
            setStartTrigger.StartDelay = 0;
            readerObj.writeData(setStartTrigger.ToString());

            Command_SetStopTrigger setStopTrigger = new Command_SetStopTrigger();
            setStopTrigger.DisableStopOnAccessCount = false;
            setStopTrigger.DisableStoponInventoryCount = true;
            setStopTrigger.DisableStopOntagcount = true;
            setStopTrigger.DisableStopOnTimeout = false;
            setStopTrigger.IgnoreHandHeldTrigger = true;
            setStopTrigger.enableStopOnAccessCount = true;
            setStopTrigger.EnableStopOnInventoryCount = false;
            setStopTrigger.EnableStopOntagcount = false;
            setStopTrigger.EnableStopOnTimeout = true;
            setStopTrigger.StopAccessCount = 1;
            setStopTrigger.StopTimeout = 5000;
            readerObj.writeData(setStopTrigger.ToString());
            await basereciverobj.isStartStopConfigSetCompltete();
            System.Diagnostics.Debug.WriteLine("setStartStopParams: " + ReaderConfig.SettingsStaus.ResponseStatusMsg);
            if (ReaderConfig.SettingsStaus.ResponseStatusMsg.Equals("OK"))
                isStartStopSet = true;
            return true;
        }

        private bool setAccessCriteria(int screen) //  parameter 'screen' represent the type of operation being performed
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                return false;
            }
            Command_SetAccessCriteria accessCriteriaFilter = new Command_SetAccessCriteria();
            accessCriteriaFilter.Accesscriteria = new Param_Accesscriteria[1];
            Param_Accesscriteria accessCriteria = new Param_Accesscriteria();
            
            if (screen == 1)
                filterEPC = (byte[])ASCIIUtil.ParseArrayFromString(TextBoxTagPatternReadWrite.Text, "byteArray", "HEX");
            else if (screen == 2)
                filterEPC = (byte[])ASCIIUtil.ParseArrayFromString(TextBoxTagPatternLock.Text, "byteArray", "HEX");
            else if (screen == 3)
                filterEPC = (byte[])ASCIIUtil.ParseArrayFromString(TectBoxTagPatternKill.Text, "byteArray", "HEX");

            if (filterEPC == null)
            {
                basereciverobj.showStatus("Access", "Invalid input: TAG ID");
                return false;
            }
            accessCriteria.filter1data = filterEPC;
            accessCriteria.filter1maskbank = ENUM_MEMORY_BANK.EPC;
            accessCriteria.filter1mask = (byte[])ASCIIUtil.ParseArrayFromString(new string('F', (filterEPC.Length) * 2), "byteArray", "HEX");
            accessCriteria.filter1maskstartpos = 2;
            accessCriteria.filter1matchlength = Convert.ToInt16(filterEPC.Length / 2);
            accessCriteria.filter1domatch = true;
            accessCriteria.filter1nomatch = false;
            accessCriteriaFilter.Accesscriteria[0] = accessCriteria;
            readerObj.writeData(accessCriteriaFilter.ToString());
            return true;
        }

        private async void ButtonWrite_Click(object sender, RoutedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                basereciverobj.showStatus(Command_Write.commandName, "No active connection with reader");
                return;
            }
            if (TextBoxTagPatternReadWrite.Text.Equals(""))
            {
                basereciverobj.showStatus(Command_Write.commandName, "Please fill TAG ID");
                return;
            }
            ReaderConfig.isAccessComplete = false;
            Command_Write writeObj = new Command_Write();
            if (TextBoxReadData.Text != "")
                writeObj.Data = (byte[])ASCIIUtil.ParseArrayFromString(TextBoxReadData.Text, "byteArray", "HEX");
            if (writeObj.Data == null)
            {
                basereciverobj.showStatus(Command_Write.commandName, "Invalid input: Write Data");
                return;
            }
            await setStartStopParams();
            if (isStartStopSet)
            {
                if (setAccessCriteria(1))
                {
                    switch (ComboBoxMemoryBankReadWrite.SelectedIndex + 1)
                    {
                        case 1:
                            writeObj.Bank = ENUM_MEMORY_BANK.EPC;
                            break;
                        case 2:
                            writeObj.Bank = ENUM_MEMORY_BANK.TID;
                            break;
                        case 3:
                            writeObj.Bank = ENUM_MEMORY_BANK.USER;
                            break;
                        case 4:
                            writeObj.Bank = ENUM_MEMORY_BANK.RESV;
                            break;
                    }
                    writeObj.CriteriaIndex = 1;
                    if (TextBoxReadOffset.Text != "")
                        writeObj.Offset = Convert.ToInt16(TextBoxReadOffset.Text);
                    if (TextBoxReadPassword.Text != "")
                        writeObj.Password = TextBoxReadPassword.Text;
                    readerObj.writeData(writeObj.ToString());
                    ReaderConfig.accessTagData.RecievedStatus = "Operation Timeout";
                    await basereciverobj.isAccessComplete();
                    FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
                    await Task.Delay(1000);
                    AcessFlyout.Hide();
                }
                else
                    ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            }
            else
                ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            await Task.Delay(1000);
            AcessFlyout.Hide();
        }

        private async void ButtonLock_Click(object sender, RoutedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                basereciverobj.showStatus(Command_Lock.commandName, "No active connection with reader");
                return;
            }
            if (TextBoxTagPatternLock.Text.Equals(""))
            {
                basereciverobj.showStatus(Command_Lock.commandName, "Please fill TAG ID");
                return;
            }
            ReaderConfig.isAccessComplete = false;
            await setStartStopParams();
            if (isStartStopSet)
            {
                if (setAccessCriteria(2))
                {
                    Command_Lock lockObj = new Command_Lock();
                    lockObj.CriteriaIndex = 1;
                    if (ComboBoxMemoryBankLock.SelectedIndex == 0)
                    {
                        if (ComboBoxLockPrivileges.SelectedIndex == 0)
                            lockObj.EpcMem = ENUM_ACCESS_PERMISSIONS.SECURED_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 1)
                            lockObj.EpcMem = ENUM_ACCESS_PERMISSIONS.ALWAYS_NOT_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 2)
                            lockObj.EpcMem = ENUM_ACCESS_PERMISSIONS.PERM_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 3)
                            lockObj.EpcMem = ENUM_ACCESS_PERMISSIONS.ACCESSIBLE;

                    }
                    if (ComboBoxMemoryBankLock.SelectedIndex == 1)
                    {
                        if (ComboBoxLockPrivileges.SelectedIndex == 0)
                            lockObj.UserMem = ENUM_ACCESS_PERMISSIONS.SECURED_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 1)
                            lockObj.UserMem = ENUM_ACCESS_PERMISSIONS.ALWAYS_NOT_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 2)
                            lockObj.UserMem = ENUM_ACCESS_PERMISSIONS.PERM_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 3)
                            lockObj.UserMem = ENUM_ACCESS_PERMISSIONS.ACCESSIBLE;

                    }
                    if (ComboBoxMemoryBankLock.SelectedIndex == 2)
                    {
                        if (ComboBoxLockPrivileges.SelectedIndex == 0)
                            lockObj.TidMem = ENUM_ACCESS_PERMISSIONS.SECURED_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 1)
                            lockObj.TidMem = ENUM_ACCESS_PERMISSIONS.ALWAYS_NOT_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 2)
                            lockObj.TidMem = ENUM_ACCESS_PERMISSIONS.PERM_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 3)
                            lockObj.TidMem = ENUM_ACCESS_PERMISSIONS.ACCESSIBLE;

                    }
                    if (ComboBoxMemoryBankLock.SelectedIndex == 3)
                    {
                        if (ComboBoxLockPrivileges.SelectedIndex == 0)
                            lockObj.KillPwd = ENUM_ACCESS_PERMISSIONS.SECURED_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 1)
                            lockObj.KillPwd = ENUM_ACCESS_PERMISSIONS.ALWAYS_NOT_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 2)
                            lockObj.KillPwd = ENUM_ACCESS_PERMISSIONS.PERM_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 3)
                            lockObj.KillPwd = ENUM_ACCESS_PERMISSIONS.ACCESSIBLE;

                    }
                    if (ComboBoxMemoryBankLock.SelectedIndex == 4)
                    {
                        if (ComboBoxLockPrivileges.SelectedIndex == 0)
                            lockObj.AccessPwd = ENUM_ACCESS_PERMISSIONS.SECURED_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 1)
                            lockObj.AccessPwd = ENUM_ACCESS_PERMISSIONS.ALWAYS_NOT_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 2)
                            lockObj.AccessPwd = ENUM_ACCESS_PERMISSIONS.PERM_ACCESSIBLE;
                        if (ComboBoxLockPrivileges.SelectedIndex == 3)
                            lockObj.AccessPwd = ENUM_ACCESS_PERMISSIONS.ACCESSIBLE;
                    }
                    if (TextBoxLockPassword.Text != "")
                        lockObj.Password = TextBoxLockPassword.Text;
                    readerObj.writeData(lockObj.ToString());
                    ReaderConfig.accessTagData.RecievedStatus = "Operation Timeout";
                    await basereciverobj.isAccessComplete();
                    FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
                    await Task.Delay(1000);
                    AcessFlyout.Hide();
                }
                else
                    ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            }
            else
                ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            await Task.Delay(1000);
            AcessFlyout.Hide();
        }

        private async void ButtonKill_Click(object sender, RoutedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                basereciverobj.showStatus(Command_Kill.commandName, "No active connection with reader");
                return;
            }
            if (TectBoxTagPatternKill.Text.Equals(""))
            {
                basereciverobj.showStatus(Command_Kill.commandName, "Please fill TAG ID");
                return;
            }
            ReaderConfig.isAccessComplete = false;
            await setStartStopParams();
            if (isStartStopSet)
            {
                if (setAccessCriteria(3))
                {
                    Command_Kill killObj = new Command_Kill();
                    killObj.CriteriaIndex = 1;
                    if (TextBoxKillPassword.Text != "")
                        killObj.Password = TextBoxKillPassword.Text;
                    readerObj.writeData(killObj.ToString());
                    ReaderConfig.accessTagData.RecievedStatus = "Operation Timeout";
                    await basereciverobj.isAccessComplete();
                    FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
                    await Task.Delay(1000);
                    AcessFlyout.Hide();
                }
                else
                    ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            }
            else
                ReaderConfig.accessTagData.RecievedStatus = ReaderConfig.SettingsStaus.ResponseStatusMsg;
            FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
            await Task.Delay(1000);
            AcessFlyout.Hide();
        }
        private void Batterybutton_Click(object sender, RoutedEventArgs e)
        {
            // navigate to battery / dpo
            this.Frame.Navigate(typeof(PageBattery));
        }
    }

}
