using ATK;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Threading.Tasks;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Navigation;

// 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 PageInventory : Page
    {
        ReaderConnect readerobj;
        BaseReciever baserecieverObj;
        List<string> MemoryBanks = new List<string>();
        public PageInventory()
        {            
            InitializeComponent();
            readerobj = ReaderConnect.getInstance();
            baserecieverObj = BaseReciever.getInstance();
            MemoryBanks.Add("NONE");
            MemoryBanks.Add("EPC");
            MemoryBanks.Add("RESERVED");
            MemoryBanks.Add("TID");
            MemoryBanks.Add("USER");
            ComboBoxMemoryBank.ItemsSource = MemoryBanks;
            ComboBoxMemoryBank.SelectedIndex =ReaderConfig.bankSelectedAtInventory;
            //TODO scrolling tag list shows blank screen at bottom
            ListViewInventoryItems.ItemsSource = ReaderConfig.inventoryRawData;
            TectBlockReadCount.DataContext = ReaderConfig.TagsRead;
            TextBlockUniqueTags.DataContext = ReaderConfig.TagsRead;
            TextBlockBatchModeMessage.DataContext = ReaderConfig.BatchMode;
            ButtonStart.DataContext = ReaderConfig.StartStopButtonStatus;
            ReaderConfig.onInventoryScreen = true;
            ComboBoxMemoryBank.DataContext= ReaderConfig.StartStopButtonStatus;
            if (!ReaderConfig.isInventoryRunning)
                ReaderConfig.BatchMode.isEnabled = false;
            TextBlockBatchModeMessage.UpdateLayout();
        }
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            ReaderConfig.onInventoryScreen = true;
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
        }

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

        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            this.Frame.Navigate(typeof(MainPage));
        }
        private void AppBarButtonGoToInventory(object sender, RoutedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            this.Frame.Navigate(typeof(PageInventory));
        }
        private void AppBarButtonGoToRapidRead(object sender, RoutedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            this.Frame.Navigate(typeof(PageRapidRead));
        }
        private void AppBarButtonGoToAccess(object sender, RoutedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            this.Frame.Navigate(typeof(PageAccess));
        }
        private void AppBarButtonGoToLocateTag(object sender, RoutedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            this.Frame.Navigate(typeof(PageLocateTag));
        }
        private void AppBarSearchButton_Click(object sender, RoutedEventArgs e)
        {
            AppBarSearch.Text = "";
            if (AppBarSearch.Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                AppBarSearch.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                ListViewInventoryItems.ItemsSource = ReaderConfig.inventoryRawData;
                TextInventory.Visibility = Windows.UI.Xaml.Visibility.Visible;
                AppBarSearchButton.Icon = new SymbolIcon(Symbol.Find);
            }
            else
            {
                AppBarSearch.Visibility = Windows.UI.Xaml.Visibility.Visible;
                TextInventory.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                AppBarSearchButton.Icon = new SymbolIcon(Symbol.Cancel);

            }
        }

        void App_BackRequested(object sender, BackRequestedEventArgs e)
        {
            ReaderConfig.onInventoryScreen = false;
            Frame.Navigate(typeof(MainPage));
        }

        private async void ButtonStart_Click(object sender, RoutedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                baserecieverObj.showStatus(Command_Inventory.commandName, "No active connection with reader");
                return;
            }
            // close search bar; get orignal tag list
            if (AppBarSearch.Visibility == Windows.UI.Xaml.Visibility.Visible)
            {
                AppBarSearch.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                ListViewInventoryItems.ItemsSource = ReaderConfig.inventoryRawData;
                TextInventory.Visibility = Windows.UI.Xaml.Visibility.Visible;
                AppBarSearchButton.Icon = new SymbolIcon(Symbol.Find);
            }
            // perform operations
            ReaderConfig.isCommandComplete = false;
            if (ButtonStart.Content.ToString() == "STOP")
            {
                baserecieverObj.abortOperation();
                TextBlockBatchModeMessage.Visibility = Visibility.Collapsed;
                ListViewInventoryItems.Visibility = Visibility.Visible;
            }
            else
            {
                ReaderConfig.bankSelectedAtInventory = ComboBoxMemoryBank.SelectedIndex;
                baserecieverObj.startInventory();
            }
            await baserecieverObj.isCommandComplete();
            if (!ReaderConfig.SettingsStaus.ResponseStatusMsg.Equals("OK") && !ReaderConfig.SettingsStaus.ResponseStatusMsg.Equals("Inventory Started in Batch Mode"))
            {
                TextInventoryStatus.Text = ReaderConfig.SettingsStaus.ResponseStatusMsg;
                FlyoutBase.ShowAttachedFlyout((FrameworkElement)sender);
                await Task.Delay(1000);
                InventoryFlyout.Hide();
            }
            if (ReaderConfig.SettingsStaus.ResponseStatusMsg.Equals("Inventory Started in Batch Mode"))
            {
                TextBlockBatchModeMessage.UpdateLayout();
            }
        }

        private void ListViewInventoryItems_ItemClick(object sender, ItemClickEventArgs e)
        {
            inventoryData clickeditem =e.ClickedItem as inventoryData;
            if (clickeditem.Visible == "Collapsed")
            {
                clickeditem.Visible = "Visible";
                ReaderConfig.selectedTagEPC.SelectedTag = clickeditem.EPCID.ToString();
                ReaderConfig.locateData.SelectedTag = clickeditem.EPCID.ToString(); ;
            }

            else
            {
                clickeditem.Visible = "Collapsed";
                ReaderConfig.selectedTagEPC.SelectedTag = "";
                ReaderConfig.locateData.SelectedTag = "";
            }
        }

        private void ComboBoxMemoryBank_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ReaderConfig.bankSelectedAtInventory = ComboBoxMemoryBank.SelectedIndex;
        }

        private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
        {
            // Only get results when it was a user typing, 
            // otherwise assume the value got filled in by TextMemberPath 
            // or the handler for SuggestionChosen.
            if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
            {
                //Set the ItemsSource to be your filtered dataset
                //sender.ItemsSource = dataset;
                string currentText = AppBarSearch.Text;
                ObservableCollection<inventoryData> inventoryList = new ObservableCollection<inventoryData>();
                IEnumerable<inventoryData> query = ReaderConfig.inventoryRawData.Where(c => string.IsNullOrEmpty(currentText) || c.EPCID.StartsWith(currentText.ToUpper()));
                foreach (inventoryData c in query)
                    inventoryList.Add(c);
                ListViewInventoryItems.ItemsSource = inventoryList;
            }
        }


        private void AutoSuggestBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
        {
            // Set sender.Text. You can use args.SelectedItem to build your text string.
        }
    }
}
