using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using ATK;
using System.Collections.ObjectModel;
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 PageRegulatory : Page
    {
        BaseReciever baseReciverObj;
        ReaderConnect readerObj;
        public ObservableCollection<Channels> frequencyChannelsAllLocal = new ObservableCollection<Channels>();
        public PageRegulatory()
        {
            int i=0;
            this.InitializeComponent();
            baseReciverObj=BaseReciever.getInstance();
            readerObj = ReaderConnect.getInstance();
            if (ReaderConfig.isReaderConnected == true)
            {                
                ComboBoxRegion.ItemsSource = ReaderConfig.regionList;
                if (ReaderConfig.isRegionSet != false)
                {
                    for (i = 0; i < ReaderConfig.regionList.Count; i++) //  get region from the region list
                    {
                        if (ReaderConfig.regionList[i].RegionCode == ReaderConfig.regultoryConfigObj.region)
                            break;
                    }
                    ComboBoxRegion.SelectedIndex = i;  // display the region
                    baseReciverObj.parseALLChannels(ReaderConfig.regionsChannelsAll[i].ChannelList); // parse channels corresponding to selected region
                    if (ReaderConfig.regionsChannelsAll[i].isHoppingCofigurable == true)  // check the selected channels
                    {
                        for (i = 0; i < ReaderConfig.frequencyChannelsAll.Count; i++)
                        {
                            for (int j = 0; j < ReaderConfig.frequencyChannelsSelected.Count; j++)
                            {
                                if (ReaderConfig.frequencyChannelsSelected[j].Channel == ReaderConfig.frequencyChannelsAll[i].Channel)
                                {
                                    ReaderConfig.frequencyChannelsAll[i].ChannelSelected = true;
                                    ReaderConfig.frequencyChannelsAll[i].ChannelEnable = true;
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        for (i = 0; i < ReaderConfig.frequencyChannelsAll.Count; i++)
                        {
                            ReaderConfig.frequencyChannelsAll[i].ChannelSelected = true;
                            ReaderConfig.frequencyChannelsAll[i].ChannelEnable = false;
                        }
                    }

                    for (i = 0; i < ReaderConfig.frequencyChannelsAll.Count; i++)
                    {
                        frequencyChannelsAllLocal.Add(new Channels { ChannelSelected = ReaderConfig.frequencyChannelsAll[i].ChannelSelected, Channel = "", ChannelEnable = false });
                    }
                    ListChannel.ItemsSource = ReaderConfig.frequencyChannelsAll;
                }
            }
        }

        /// <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)
        {
            //Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;
            SystemNavigationManager.GetForCurrentView().BackRequested += App_BackRequested;
        }

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


        private void AppBarButton_Click(object sender, RoutedEventArgs e)
        {
            sendRegulatoryConfig();
            this.Frame.Navigate(typeof(PageSettings));
        }

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

        // TODO UI combo box selection doesn not open region list everytime, select region will not result in selection
        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (ReaderConfig.isReaderConnected == false)
            {
                baseReciverObj.showStatus(Command_SetRegulatory.commandName, "No active connection with reader");
                return;
            }
            baseReciverObj.parseALLChannels(ReaderConfig.regionsChannelsAll[ComboBoxRegion.SelectedIndex].ChannelList);
            if (!ReaderConfig.regionsChannelsAll[ComboBoxRegion.SelectedIndex].isHoppingCofigurable)
            {
                for (int i = 0; i < ReaderConfig.frequencyChannelsAll.Count; i++)
                {
                    ReaderConfig.frequencyChannelsAll[i].ChannelSelected = true;
                    ReaderConfig.frequencyChannelsAll[i].ChannelEnable = false;
                }
            }
            ListChannel.ItemsSource = null;
            ListChannel.ItemsSource = ReaderConfig.frequencyChannelsAll;
        }
        public string createChannelsString(ObservableCollection<Channels> channelList)
        {
            bool firstOccurence = false;
            string sb="";
            foreach(var channel in channelList)
            {
                if(channel.ChannelSelected==true)
                {                    
                    if (firstOccurence == false)
                        sb = channel.Channel;
                    else
                        sb = sb + "," + channel.Channel;
                    firstOccurence = true;
                }               
            }
            return sb;
        }

        public async void sendRegulatoryConfig()
        {
            if (!ReaderConfig.isReaderConnected || ReaderConfig.BatchMode.isEnabled || ComboBoxRegion.SelectedIndex < 0)
            {
                return;
            }
            
            bool sendCommand = false;
            if (ReaderConfig.regionList[ComboBoxRegion.SelectedIndex].RegionCode != ReaderConfig.regultoryConfigObj.region) // if region has changed
            {
                sendCommand = true;
            }
            if (!sendCommand)
            {
                for (int ctr = 0; ctr < frequencyChannelsAllLocal.Count; ctr++)// if any frequency selection has changed
                {
                    if (frequencyChannelsAllLocal[ctr].ChannelSelected != ReaderConfig.frequencyChannelsAll[ctr].ChannelSelected)
                    {
                        sendCommand = true;
                        break;
                    }
                }
            }
            if (sendCommand)
            {
                Command_SetRegulatory regultoryConfigOnj = new Command_SetRegulatory();
                regultoryConfigOnj.region = ReaderConfig.regionList[ComboBoxRegion.SelectedIndex].RegionCode;
                if(ReaderConfig.regionsChannelsAll[ComboBoxRegion.SelectedIndex].isHoppingCofigurable==true)
                     regultoryConfigOnj.enabledchannels = createChannelsString(ReaderConfig.frequencyChannelsAll);
                readerObj.writeData(regultoryConfigOnj.ToString());
                await baseReciverObj.isConfigSaved();
                // region was set properly
                if (ReaderConfig.isConfigSaved)
                {
                    if (ReaderConfig.moveToRegioScreen == true)
                    {
                        readerObj.getInitialConfig(false);
                        ReaderConfig.moveToRegioScreen = false;
                    }
                    else
                        readerObj.writeData(ASCIIProcessor.getCommandConfig(regultoryConfigOnj.getCommandType(), CONFIG_TYPE.CURRENT));
                }
                ReaderConfig.isConfigSaved = false;
            }
        }        
    }

}
