using Windows.UI.Xaml;

using Windows.UI.Xaml.Controls;

using Windows.UI.Xaml.Navigation;

using ATK;

using System;

using System.Collections.Generic;

using Windows.UI.Core;

using System.Threading.Tasks;

using Windows.UI.Xaml.Controls.Primitives;



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

    {

        ReaderConnect readerObj;

        BaseReciever basereciverobj;

        List<string> memoryBank = new List<string>();

        List<string> target = new List<string>();

        List<string> actions = new List<string>();

        private readonly short BITS_IN_WORD = 16;



        public PageFilters()

        {

            this.InitializeComponent();

            readerObj = ReaderConnect.getInstance();

            basereciverobj = BaseReciever.getInstance();

            memoryBank.Add("EPC");

            memoryBank.Add("TID");

            memoryBank.Add("USER");

            ComboFilter1MemoryBank.ItemsSource = memoryBank;

            ComboFilter2MemoryBank.ItemsSource = memoryBank;



            actions.Add("INV_A_NOT_INV_B_OR_ASRT_SL_NOT_DSRT_SL");

            actions.Add("INV_A_OR_ASRT_SL");

            actions.Add("NOT_INV_B_OR_NOT_DSRT_SL");

            actions.Add("INV_A2BB2A_NOT_INV_A_OR_NEG_SL_NOT_ASRT_SL");

            actions.Add("INV_B_NOT_INV_A_OR_DSRT_SL_NOT_ASRT_SL");

            actions.Add("INV_B_OR_DSRT_SL");

            actions.Add("NOT_INV_A_OR_NOT_ASRT_SL");

            actions.Add("NOT_INV_A2BB2A_OR_NOT_NEG_SL");

            ComboFilter1Action.ItemsSource = actions;

            ComboFilter2Action.ItemsSource = actions;



            target.Add("SESSION S0");

            target.Add("SESSION S1");

            target.Add("SESSION S2");

            target.Add("SESSION S3");

            target.Add("SL FLAG");

            ComboFilter1Target.ItemsSource = target;

            ComboFilter2Target.ItemsSource = target;

            setIntialPreFilters();



            BatteryDPO.DataContext = ReaderConfig.batteryDPO;

        }



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

        {

            setIntialPreFilters();

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

        {

            sendPreFilters(sender);

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

        }

        private void AppBarButtonGoToInventory(object sender, RoutedEventArgs e)

        {

            sendPreFilters(sender);

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

        }



        private void AppBarButtonGoToRapidRead(object sender, RoutedEventArgs e)

        {

            sendPreFilters(sender);

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

        }



        private void AppBarButtonGoToAccess(object sender, RoutedEventArgs e)

        {

            sendPreFilters(sender);

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

        }



        private void AppBarButtonGoToLocateTag(object sender, RoutedEventArgs e)

        {

            sendPreFilters(sender);

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

        }



        void App_BackRequested(object sender, BackRequestedEventArgs e)

        {

            sendPreFilters(sender);

            Frame.Navigate(typeof(MainPage));

        }

        void setIntialPreFilters()

        {

            if (ReaderConfig.selectFilterParams.SelectRecord != null)

            {

                if (ReaderConfig.selectFilterParams.SelectRecord.Length > 0)

                {

                    ToggelFilter1.IsOn = true;

                    if (ReaderConfig.selectFilterParams.SelectRecord[0].MatchPattern != null)

                        TextBoxMatchPatternFilter1.Text = ASCIIUtil.ConvertArrayToString(ReaderConfig.selectFilterParams.SelectRecord[0].MatchPattern, "byteArray", "HEX").ToString();

                    TextBoxFilter1Offset.Text = (ReaderConfig.selectFilterParams.SelectRecord[0].MaskStartPos / BITS_IN_WORD).ToString();

                    ComboFilter1MemoryBank.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[0].MaskBank);

                    ComboFilter1Target.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[0].Target);

                    ComboFilter1Action.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[0].Action);

                }

                if (ReaderConfig.selectFilterParams.SelectRecord.Length > 1)

                {

                    ToggelFilter2.IsOn = true;

                    if (ReaderConfig.selectFilterParams.SelectRecord[1].MatchPattern != null)

                        TextBoxMatchPatternFilter2.Text = ASCIIUtil.ConvertArrayToString(ReaderConfig.selectFilterParams.SelectRecord[1].MatchPattern, "byteArray", "HEX").ToString();

                    TextBoxFilter2Offset.Text = (ReaderConfig.selectFilterParams.SelectRecord[1].MaskStartPos / BITS_IN_WORD).ToString();

                    ComboFilter2MemoryBank.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[1].MaskBank);

                    ComboFilter2Target.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[1].Target);

                    ComboFilter2Action.SelectedIndex = Convert.ToInt32(ReaderConfig.selectFilterParams.SelectRecord[1].Action);

                }

            }

        }



        private async void sendPreFilters(object sender)

        {

            if (ReaderConfig.isReaderConnected == false)

            {

                return;

            }

            Command_SetSelectRecords setSelectRecordObj = new Command_SetSelectRecords();

            setSelectRecordObj.SelectRecord = new Param_SelectRecord[2];

            Param_SelectRecord selectrecordFilter1 = new Param_SelectRecord();

            Param_SelectRecord selectrecordFilter2 = new Param_SelectRecord();

            if (TextBoxFilter1Offset.Text != "")

                selectrecordFilter1.MaskStartPos = (short)(Convert.ToInt16(TextBoxFilter1Offset.Text) * BITS_IN_WORD);

            if (TextBoxMatchPatternFilter1.Text != "")

            {

                selectrecordFilter1.MatchPattern = (byte[])ASCIIUtil.ParseArrayFromString(TextBoxMatchPatternFilter1.Text, "byteArray", "HEX");

                if (selectrecordFilter1.MatchPattern == null)

                {

                    basereciverobj.showStatus("Pre Filter", "Invalid input: MatchPattern");

                    return;

                }

                selectrecordFilter1.MatchLength = Convert.ToInt16(selectrecordFilter1.MatchPattern.Length * 8);

            }



            switch (ComboFilter1MemoryBank.SelectedIndex + 1)

            {

                case 1:

                    selectrecordFilter1.MaskBank = ENUM_MEMORY_BANK.EPC;

                    break;

                case 2:

                    selectrecordFilter1.MaskBank = ENUM_MEMORY_BANK.TID;

                    break;

                case 3:

                    selectrecordFilter1.MaskBank = ENUM_MEMORY_BANK.USER;

                    break;

            }

            switch (ComboFilter1Target.SelectedIndex + 1)

            {

                case 1:

                    selectrecordFilter1.Target = ENUM_TARGET.SESSION_S0;

                    break;

                case 2:

                    selectrecordFilter1.Target = ENUM_TARGET.SESSION_S1;

                    break;

                case 3:

                    selectrecordFilter1.Target = ENUM_TARGET.SESSION_S2;

                    break;

                case 4:

                    selectrecordFilter1.Target = ENUM_TARGET.SESSION_S3;

                    break;

                case 5:

                    selectrecordFilter1.Target = ENUM_TARGET.SL_FLAG;

                    break;

            }

            switch (ComboFilter1Action.SelectedIndex)

            {

                case 0:

                    selectrecordFilter1.Action = ENUM_ACTION.INV_A_NOT_INV_B_OR_ASRT_SL_NOT_DSRT_SL;

                    break;

                case 1:

                    selectrecordFilter1.Action = ENUM_ACTION.INV_A_OR_ASRT_SL;

                    break;

                case 2:

                    selectrecordFilter1.Action = ENUM_ACTION.NOT_INV_B_OR_NOT_DSRT_SL;

                    break;

                case 3:

                    selectrecordFilter1.Action = ENUM_ACTION.INV_A2BB2A_NOT_INV_A_OR_NEG_SL_NOT_ASRT_SL;

                    break;

                case 4:

                    selectrecordFilter1.Action = ENUM_ACTION.INV_B_NOT_INV_A_OR_DSRT_SL_NOT_ASRT_SL;

                    break;

                case 5:

                    selectrecordFilter1.Action = ENUM_ACTION.INV_B_OR_DSRT_SL;

                    break;

                case 6:

                    selectrecordFilter1.Action = ENUM_ACTION.NOT_INV_A_OR_NOT_ASRT_SL;

                    break;

                case 7:

                    selectrecordFilter1.Action = ENUM_ACTION.NOT_INV_A2BB2A_OR_NOT_NEG_SL;

                    break;

            }



            if (TextBoxFilter2Offset.Text != "")

                selectrecordFilter2.MaskStartPos = (short)(Convert.ToInt16(TextBoxFilter2Offset.Text) * BITS_IN_WORD);

            if (TextBoxMatchPatternFilter2.Text != "")

            {

                selectrecordFilter2.MatchPattern = (byte[])ASCIIUtil.ParseArrayFromString(TextBoxMatchPatternFilter2.Text, "byteArray", "HEX");

                if (selectrecordFilter2.MatchPattern == null)

                {

                    basereciverobj.showStatus("Pre Filter", "Invalid input: MatchPattern");

                    return;

                }

                selectrecordFilter2.MatchLength = Convert.ToInt16(selectrecordFilter2.MatchPattern.Length * 8);

            }



            switch (ComboFilter2MemoryBank.SelectedIndex + 1)

            {

                case 1:

                    selectrecordFilter2.MaskBank = ENUM_MEMORY_BANK.EPC;

                    break;

                case 2:

                    selectrecordFilter2.MaskBank = ENUM_MEMORY_BANK.TID;

                    break;

                case 3:

                    selectrecordFilter2.MaskBank = ENUM_MEMORY_BANK.USER;

                    break;

            }

            switch (ComboFilter2Target.SelectedIndex + 1)

            {

                case 1:

                    selectrecordFilter2.Target = ENUM_TARGET.SESSION_S0;

                    break;

                case 2:

                    selectrecordFilter2.Target = ENUM_TARGET.SESSION_S1;

                    break;

                case 3:

                    selectrecordFilter2.Target = ENUM_TARGET.SESSION_S2;

                    break;

                case 4:

                    selectrecordFilter2.Target = ENUM_TARGET.SESSION_S3;

                    break;

                case 5:

                    selectrecordFilter2.Target = ENUM_TARGET.SL_FLAG;

                    break;

            }

            switch (ComboFilter2Action.SelectedIndex)

            {

                case 0:

                    selectrecordFilter2.Action = ENUM_ACTION.INV_A_NOT_INV_B_OR_ASRT_SL_NOT_DSRT_SL;

                    break;

                case 1:

                    selectrecordFilter2.Action = ENUM_ACTION.INV_A_OR_ASRT_SL;

                    break;

                case 2:

                    selectrecordFilter2.Action = ENUM_ACTION.INV_A2BB2A_NOT_INV_A_OR_NEG_SL_NOT_ASRT_SL;

                    break;

                case 3:

                    selectrecordFilter2.Action = ENUM_ACTION.INV_B_NOT_INV_A_OR_DSRT_SL_NOT_ASRT_SL;

                    break;

                case 4:

                    selectrecordFilter2.Action = ENUM_ACTION.INV_B_OR_DSRT_SL;

                    break;

                case 5:

                    selectrecordFilter2.Action = ENUM_ACTION.NOT_INV_A_OR_NOT_ASRT_SL;

                    break;

                case 6:

                    selectrecordFilter2.Action = ENUM_ACTION.NOT_INV_A2BB2A_OR_NOT_NEG_SL;

                    break;

                case 7:

                    selectrecordFilter2.Action = ENUM_ACTION.NOT_INV_B_OR_NOT_DSRT_SL;

                    break;

            }



            if ((ToggelFilter1.IsOn == true) && (ToggelFilter2.IsOn == true))

            {

                setSelectRecordObj.SelectRecord[0] = selectrecordFilter1;

                setSelectRecordObj.SelectRecord[1] = selectrecordFilter2;

                ReaderConfig.isSelectRecordSet = true;

            }



            if ((ToggelFilter1.IsOn == true) && (ToggelFilter2.IsOn == false))

            {

                setSelectRecordObj.SelectRecord[0] = selectrecordFilter1;

                setSelectRecordObj.SelectRecord[1] = null;

                ReaderConfig.isSelectRecordSet = true;

            }



            if ((ToggelFilter1.IsOn == false) && (ToggelFilter2.IsOn == true))

            {

                setSelectRecordObj.SelectRecord[0] = selectrecordFilter2;

                setSelectRecordObj.SelectRecord[1] = null;

                ReaderConfig.isSelectRecordSet = true;

            }



            if ((ToggelFilter1.IsOn == false) && (ToggelFilter2.IsOn == false))

            {

                setSelectRecordObj.SelectRecord[0] = null;

                setSelectRecordObj.SelectRecord[1] = null;

                ReaderConfig.isSelectRecordSet = false;

            }

            bool sendcommand = false;

            int len = setSelectRecordObj.SelectRecord[0] == null ? 0 : 1;

            if (setSelectRecordObj.SelectRecord[1] != null)

                len = 2;

            int ReaderLength = ReaderConfig.selectFilterParams.SelectRecord == null ? 0 : ReaderConfig.selectFilterParams.SelectRecord.Length;

            if (ReaderLength != len)

                sendcommand = true;

            else if (len == 1 && !compareSelectRecord(ReaderConfig.selectFilterParams.SelectRecord[0], setSelectRecordObj.SelectRecord[0]))

                sendcommand = true;

            else if (len == 2 && (!compareSelectRecord(ReaderConfig.selectFilterParams.SelectRecord[0], setSelectRecordObj.SelectRecord[0]) || !compareSelectRecord(ReaderConfig.selectFilterParams.SelectRecord[1], setSelectRecordObj.SelectRecord[1])))

                sendcommand = true;



            if (sendcommand)

            {

                readerObj.writeData(setSelectRecordObj.ToString());

                await basereciverobj.isPreFilterConfigSetComplete();

                readerObj.writeData(ASCIIProcessor.getCommandConfig(setSelectRecordObj.getCommandType(), CONFIG_TYPE.CURRENT));

            }

        }



        //TODO: move this to SDK for equal operator override

        private bool compareSelectRecord(Param_SelectRecord param_SelectRecord1, Param_SelectRecord param_SelectRecord2)

        {

            if (param_SelectRecord1.Action != param_SelectRecord2.Action)

                return false;

            if (param_SelectRecord1.MaskBank != param_SelectRecord2.MaskBank)

                return false;

            if (param_SelectRecord1.MaskStartPos != param_SelectRecord2.MaskStartPos)

                return false;

            if (param_SelectRecord1.MatchPattern != null && (param_SelectRecord1.MatchLength != param_SelectRecord2.MatchLength))

                return false;

            if (param_SelectRecord1.Target != param_SelectRecord2.Target)

                return false;

            if (param_SelectRecord1.MatchPattern != null)

                for (int i = 0; i < param_SelectRecord1.MatchLength / 8; i++)

                    if (param_SelectRecord1.MatchPattern[i] != param_SelectRecord2.MatchPattern[i])

                        return false;

            return true;



        }



        private void Batterybutton_Click(object sender, RoutedEventArgs e)

        {

            // navigate to battery / dpo

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

        }

    }

}



