using System.Threading.Tasks;

using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Controls.Primitives;

using Windows.UI.Xaml.Navigation;

using ATK;

using System;



// bluetooth RFCMM reference



// 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 PageReaderList : Page

    {

        private ReaderConnect readerobj;

        private BaseReciever baseRecieverObj;

        public PageReaderList()

        {

            InitializeComponent();

            readerobj = ReaderConnect.getInstance();

            baseRecieverObj = BaseReciever.getInstance();

            textConnectLabel.Text = "Connection password required!";

            ListViewReaders.ItemsSource = readerobj.items;

        }



        private async void PopulateDevices()

        {

            if (readerobj.items.Count == 0)

            {

                await readerobj.findpaireddevicesnew();

            }

        }



        /// <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)

        {

            PopulateDevices();

            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;

        }



        protected override void OnNavigatedFrom(NavigationEventArgs e)

        {

            base.OnNavigatedFrom(e);

            //Windows.Phone.UI.Input.HardwareButtons.BackPressed -= HardwareButtons_BackPressed;

        }





        private void AppBarButton_Click(object sender, RoutedEventArgs e)

        {

            this.Frame.Navigate(typeof(PageSettings));

        }





        void HardwareButtons_BackPressed(object sender)

        {

            Frame.Navigate(typeof(PageSettings));



        }



        private void GoTo_Settings_Click(object sender, RoutedEventArgs e)

        {

            this.Frame.Navigate(typeof(PageSettings));

        }



        private async void ListViewReaders_ItemClick(object sender, ItemClickEventArgs e)

        {

            // Disable list view while in process

            disableUI();

            // mark reader is selected

            readerobj.readerSelected = true;

            // if reconnection is going on wait

            if (readerobj.reConnectionRetries > 0)

            {

                int loopCount = 0;

                while (readerobj.reConnectionRetries != 0 && loopCount < 5)

                {

                    await Task.Delay(500);

                    loopCount++;

                }

            }

            // process selection

            readerinfo clickedItem = e.ClickedItem as readerinfo;

            if (ReaderConfig.isReaderConnected == true)

            {

                if (clickedItem.DisplayName.CompareTo(readerobj.getDeviceName(ReaderConfig.connectedReaderIndex)) == 0)

                {

                    await readerobj.disconnect();

                    enableUI();

                    return;

                }

                else

                {

                    textflyout.Text = clickedItem.DisplayName;

                    FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);

                    await readerobj.disconnect();

                }

            }

            else

            {

                textflyout.Text = clickedItem.DisplayName;

                FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);

            }



            if (await readerobj.connectToDevice(clickedItem) != 1)

            {

                flyout1.Hide();

                enableUI();

                readerobj.showStatus(clickedItem.DisplayName, "Connection Error!");

                return;

            }

            await baseRecieverObj.isConnectComplete();

            if (ReaderConfig.isConnectWithPasswordEnabled == true)

            {

                flyout1.Hide();

                PopUpPassword.IsOpen = true;

                disableUI();

            }

            else

            {

                await readerobj.GetInitialConfiguration();

                flyout1.Hide();

                // Enable list view UI

                enableUI();

                if (MainPage.isApplicationWindowActive && ReaderConfig.connectionConfig.readerConnection)

                    readerobj.showStatus(clickedItem.DisplayName, "Connected");



            }

        }



        private void disableUI()

        {

            ButtonGoToSettings.IsEnabled = false;

            ListViewReaders.IsEnabled = false;

        }



        private void enableUI()

        {

            ButtonGoToSettings.IsEnabled = true;

            ListViewReaders.IsEnabled = true;

        }



        private async void ButtonPasswordConnectCommand_Click(object sender, RoutedEventArgs e)

        {

            Command_Connect connectCommand = new Command_Connect();

            if (TextPassword != null)

            {

                connectCommand.password = TextPassword.Text;

                ReaderConfig.connectionPassword = TextPassword.Text;

            }

            readerobj.writeData(connectCommand.ToString());

            ReaderConfig.isConnectComplete = false;

            await baseRecieverObj.isConnectComplete();



            if (ReaderConfig.isConnectWithPasswordEnabled == false)

            {

                PopUpPassword.IsOpen = false;

                enableUI();



                if (ReaderConfig.isBatchModeEventRecieved == false)

                {

                    await readerobj.isRegionSet();

                    if (ReaderConfig.moveToRegioScreen == true)

                    {

                        await baseRecieverObj.isGetAllRegionInfoComplete();

                        ReaderConfig.isGetAllRegionsInfoComplete = false;

                        this.Frame.Navigate(typeof(PageRegulatory));

                    }

                    else

                    {

                        readerobj.getInitialConfig(true);

                        await baseRecieverObj.isInitialSettingsRecievedComplete();

                    }

                }

            }

            else

                textConnectLabel.Text = " Invalid Password! Reenter";

            ReaderConfig.isConnectWithPasswordEnabled = false;

        }



        private void ButtonPasswordCancelCommand_Click(object sender, RoutedEventArgs e)

        {

            PopUpPassword.IsOpen = false;

            enableUI();

            readerobj.disconnect();

        }



    }

}



