using System;

using System.Linq;

using System.Threading.Tasks;

using ATK;

using Windows.UI.Popups;

using Windows.UI.Xaml.Media.Imaging;

using Windows.UI.Xaml;

using Windows.Data.Xml.Dom;

using Windows.UI.Core;

using Windows.Storage;

using System.Collections.ObjectModel;



namespace Zebra_RFID_Mobile

{

    /* Summary for: BaseReciever

     1) parses all data that is recieved after SDK parsing and performs data binding for UI elements                

    */

    class BaseReciever

    {

        ReaderConnect readerobj;

        private BaseReciever() { }



        //create an object of SingleObject

        private static BaseReciever instance = new BaseReciever();



        //Get the only object available

        public static BaseReciever getInstance()

        {

            if (instance == null)

            {

                instance = new BaseReciever();

            }

            return instance;

        }



        /* Summary for: parseALLChannels

         1) parses all channels and fills appropriate channel list(all channel list)         

        Input : channelString=> string from which the channels are extracted

        Output : none            

        */

        public void parseALLChannels(string channelString)

        {

            char delimiter = ' ';

            string[] substrings = channelString.Split(delimiter);

            ReaderConfig.frequencyChannelsAll.Clear();

            foreach (var substring in substrings)

            {

                Channels dummychannel = new Channels();

                if (substring != "")

                {

                    dummychannel.Channel = substring;

                    dummychannel.ChannelSelected = false;

                    dummychannel.ChannelEnable = true;

                    ReaderConfig.frequencyChannelsAll.Add(dummychannel);

                }

            }



        }



        /* Summary for: parseSlectedChannels

         1) parses  channels and fills appropriate channel list(selected channel list)         

        Input : channelString=> string from which the channels are extracted

        Output : none            

      */

        public void parseSlectedChannels(string channelString)

        {

            char delimiter = ' ';

            string[] substrings = channelString.Split(delimiter);

            ReaderConfig.frequencyChannelsSelected.Clear();

            foreach (var substring in substrings)

            {

                Channels dummychannel = new Channels();

                dummychannel.Channel = substring;

                dummychannel.ChannelSelected = true;

                dummychannel.ChannelEnable = true;

                ReaderConfig.frequencyChannelsSelected.Add(dummychannel);

            }

        }



        /* Summary for: configurationFromReader

            1) handles all the "noexec" data

            2) this data is used to fill all settings screens

            Input : msg=> noexec msg(type:IMsg)

            Output : none            

        */

        public void configurationFromReader(IMsg msg) // handles settings response data(noexe data)

        {

            if (msg is Command_SetAntennaConfiguration)

            {

                ReaderConfig.antennaConfigParams = (Command_SetAntennaConfiguration)msg;

            }

            else if (msg is Command_SetAccessCriteria)

            {

                ReaderConfig.accessCriteriaParams = (Command_SetAccessCriteria)msg;

            }

            else if (msg is Command_SetSelectRecords)

            {

                ReaderConfig.selectFilterParams = (Command_SetSelectRecords)msg;

                if (ReaderConfig.selectFilterParams.SelectRecord != null && ReaderConfig.selectFilterParams.SelectRecord.Length > 0)

                    ReaderConfig.isSelectRecordSet = true;

                else

                    ReaderConfig.isSelectRecordSet = false;

            }

            else if (msg is Command_SetQueryParams)

            {

                ReaderConfig.queryParams = (Command_SetQueryParams)msg;

            }

            else if (msg is Command_SetStartTrigger)

            {

                ReaderConfig.startTriggerParams = ((Command_SetStartTrigger)msg);

            }

            else if (msg is Command_SetStopTrigger)

            {

                ReaderConfig.stopTriggerParams = ((Command_SetStopTrigger)msg);

            }

            else if (msg is Command_SetReportConfig)

            {

                ReaderConfig.reportConfigParams = ((Command_SetReportConfig)msg);

            }

            else if (msg is Command_SetUniqueReport)

            {

                Command_SetUniqueReport cmdUniqueReport = ((Command_SetUniqueReport)msg);

                ReaderConfig.reportUniqueTags = cmdUniqueReport.Enable;

            }

            else if (msg is Command_SetDynamicPower)

            {

                Command_SetDynamicPower dynamicpower = (Command_SetDynamicPower)msg;

                if (dynamicpower.Disable == true)

                {

                    ReaderConfig.isDynmaicPowerEnabled = false;

                    Uri imageURI = new Uri("ms-appx:///Assets/title_dpo_disabled.png", UriKind.Absolute);

                    BitmapImage dpoImage = new BitmapImage(imageURI);

                    ReaderConfig.DPOImage.DPOImage = dpoImage;

                }

                if (dynamicpower.Enable == true)

                {

                    ReaderConfig.isDynmaicPowerEnabled = true;

                    Uri imageURI = new Uri("ms-appx:///Assets/title_dpo_enabled.png", UriKind.Absolute);

                    BitmapImage dpoImage = new BitmapImage(imageURI);

                    ReaderConfig.DPOImage.DPOImage = dpoImage;

                }

            }

            else if (msg is Command_SetRegulatory)

            {



                Command_SetRegulatory setRegulatoryObj = (Command_SetRegulatory)msg;

                if (setRegulatoryObj.region.ToUpper().Trim() == "NA")

                {

                    ReaderConfig.isRegionSet = false;

                    ReaderConfig.isRegionGetComplete = true;

                    return;

                }

                else

                {

                    ReaderConfig.isRegionSet = true;

                }

                ReaderConfig.isRegionGetComplete = true;

                ReaderConfig.regultoryConfigObj = setRegulatoryObj;

                parseSlectedChannels(ReaderConfig.regultoryConfigObj.enabledchannels);

            }

        }





        internal void responseMetaDataParsed(Response_Status MetadataResponse)

        {

            if (MetadataResponse.command.Equals(Command_Inventory.commandName.ToLower()) ||

                MetadataResponse.command.Equals(Command_LocateTag.commandName.ToLower()) ||

                MetadataResponse.command.Equals(Command_Read.commandName.ToLower()))

            {

                if (MetadataResponse.Status == "OK")

                {

                    ReaderConfig.isCommandComplete = true;

                }

            }

        }



        /* Summary for: responseDataParsedFromGenericReader

          1) Handles actual data from the reader(like tagdata, get responses, locate data)   

         Input : msg=> response msg(type:IMsg)

         Output : none            

       */

        public void responseDataParsedFromGenericReader(ResponseMsg responseMsg) //handles the actual data.. 

        {                                                                       // data here is already in corresponding obj classes

            try

            {

                switch (responseMsg.getResponseType())

                {

                    case RESPONSE_TYPE.ATTRIBUTEINFO:

                        Response_AttributeInfo attrInfoObj = (Response_AttributeInfo)responseMsg;

                        if (attrInfoObj.AttNum == 140) // beeper settings

                        {

                            if (attrInfoObj.Value == 3)

                            {

                                ReaderConfig.isBeeperOn = false;

                            }

                            else

                            {

                                ReaderConfig.isBeeperOn = true;

                                if (attrInfoObj.Value == 0)

                                {

                                    ReaderConfig.beeperLevel = ENUM_BEEPER_VOLUME.HIGH_BEEP;

                                }

                                else if (attrInfoObj.Value == 1)

                                {

                                    ReaderConfig.beeperLevel = ENUM_BEEPER_VOLUME.MEDIUM_BEEP;

                                }

                                else if (attrInfoObj.Value == 2)

                                {

                                    ReaderConfig.beeperLevel = ENUM_BEEPER_VOLUME.LOW_BEEP;

                                }

                            }

                        }



                        if (attrInfoObj.AttNum == 1500)

                        {

                            ReaderConfig.batchmode = attrInfoObj.Value;

                        }

                        break;

                    case RESPONSE_TYPE.CAPABILITIES:

                        Response_Capabilities CapabilitiesResponse = (Response_Capabilities)responseMsg;

                        readerobj = ReaderConnect.getInstance();

                        if (CapabilitiesResponse.Name.Equals("MODEL_NAME"))

                        {

                            ReaderConfig.DeviceModel = CapabilitiesResponse.Value;

                            readerobj.items[ReaderConfig.connectedReaderIndex].ModelDisplayName = ReaderConfig.DeviceModel;

                        }

                        else if (CapabilitiesResponse.Name.Equals("SERIAL_NUMBER"))

                        {

                            ReaderConfig.DeviceSerial = CapabilitiesResponse.Value;

                            readerobj.items[ReaderConfig.connectedReaderIndex].SerialDisplayName = ReaderConfig.DeviceSerial;

                        }

                        break;

                    case RESPONSE_TYPE.REGULATORYCONFIG: // response for gr.c

                        Response_RegulatoryConfig response_regulatory = (Response_RegulatoryConfig)responseMsg;

                        ReaderConfig.regionsChannelsAll.Add(new Regions_Channels { ChannelList = response_regulatory.SupportedChannels, RegionCode = response_regulatory.RegionCode, isHoppingCofigurable = response_regulatory.HoppingConfigurable });

                        if ((response_regulatory.RegionCode.Trim().ToUpper() == ReaderConfig.lastRegion.ToUpper()) && (ReaderConfig.lastRegion != ""))

                        {

                            ReaderConfig.isGetAllRegionsInfoComplete = true;

                        }

                        break;

                    case RESPONSE_TYPE.STATUS:

                        Response_Status response_Status = (Response_Status)responseMsg;

                        handleStatusMessages(response_Status);

                        break;

                    case RESPONSE_TYPE.SUPPORTEDLINKPROFILES:

                        Response_SupportedLinkProfiles response_LinkProfiles = (Response_SupportedLinkProfiles)responseMsg;



                        ReaderConfig.linkProfiles.Add(response_LinkProfiles.BDR.ToString() + " " + response_LinkProfiles.M.ToString() + " " + response_LinkProfiles.PIE.ToString() + " "

                            + response_LinkProfiles.MinTari.ToString() + " " + response_LinkProfiles.MaxTari.ToString() + " " + response_LinkProfiles.StepTari.ToString());



                        ReaderConfig.linkProfilesWithIndex.Add(new LinkProfile

                        {

                            RFindex = response_LinkProfiles.RFModeIndex,

                            LProfile = response_LinkProfiles.RFModeIndex.ToString() + " " + response_LinkProfiles.BDR.ToString() + " "

                            + response_LinkProfiles.M.ToString() + " " + response_LinkProfiles.PIE.ToString() + " " + response_LinkProfiles.MinTari.ToString() + " "

                            + response_LinkProfiles.MaxTari.ToString() + " " + response_LinkProfiles.StepTari.ToString()

                        });

                        break;

                    case RESPONSE_TYPE.SUPPORTEDREGIONS:

                        Response_SupportedRegions response_SupportedRegions = (Response_SupportedRegions)responseMsg;

                        ReaderConfig.regionList.Add(new Regions { Region = response_SupportedRegions.Name, RegionCode = response_SupportedRegions.RegionCode });

                        break;

                    case RESPONSE_TYPE.TAGDATA:

                        Response_TagData response_tagData = (Response_TagData)responseMsg;

                        if (ReaderConfig.isInventoryScreenTagData == true) // if inventory is running.. handle the inventory data

                        {                                                //Note(ToDo): as the isInventoryScreenTagData is false soon after stop , tags recieved after this act as access data!!?? 

                            handleInventortyData(response_tagData);

                        }

                        else //handle the access screen data

                        {

                            handleAccessData(response_tagData);



                        }

                        break;

                    case RESPONSE_TYPE.TAGPROXIMITYPERCENT:

                        Response_TagProximityPercent locateData = (Response_TagProximityPercent)responseMsg;

                        ReaderConfig.locateData.LocateData = locateData.Proximitypercent;



                        break;

                    case RESPONSE_TYPE.VERSIONINFO:

                        Response_VersionInfo versionData = (Response_VersionInfo)responseMsg;

                        if (versionData.Device.ToUpper().Trim() == "GENX_DEVICE")

                            ReaderConfig.versionInfo.Module = versionData.Version.ToString();

                        if (versionData.Device.ToUpper().Trim() == "NGE")

                            ReaderConfig.versionInfo.Radio = versionData.Version.ToString();

                        ReaderConfig.isInitialSettingsRecieved = true;

                        break;

                    default:

                        break;

                }

            }

            catch (Exception e)

            {

                string str = e.Message;

            }

        }



        public int num = 0;

        /* Summary for: handleStatusMessages

            1) Handle status messages for all commands and maintains all the internal states.

            2) Don't return for cases where the error needs to be displayed  

            * settings screen do not have internal states, hence can be handled together

           Input : response_status message

           Output : none            

         */

        public async void handleStatusMessages(Response_Status responseStatusMsg)

        {



            if (responseStatusMsg == null || responseStatusMsg.command == null)

                return;

            else

            {

                // copy response for internal UI validation purpose

                // TODO clear status; incase of failure previous message shown at other UI/button checking places

                ReaderConfig.SettingsStaus.ResponseStatusMsg = responseStatusMsg.Status;

                System.Diagnostics.Debug.WriteLine("handleStatusMessages: " + ReaderConfig.SettingsStaus.ResponseStatusMsg);

            }





            if (responseStatusMsg.command.Trim() == Command_GetTags.commandName.ToLower())

            {

                readerobj.writeData(new Command_PurgeTags().ToString());

                ReaderConfig.isInventoryScreenTagData = false;

                return;

            }

            else if (responseStatusMsg.command.Trim() == Command_PurgeTags.commandName.ToLower() && ReaderConfig.isGetTagsData)

            {

                //TODO show flyout when getting reader settings after batch mode purge

                if (ReaderConfig.isInitialSettingsRecieved == false)

                    readerobj.getInitialConfig(true);

                ReaderConfig.isGetTagsData = false;

            }

            else if (responseStatusMsg.command == Command_abort.commandName)

            {

                if (responseStatusMsg.Status == "OK")

                {

                    if (ReaderConfig.isLocateRunning == true)

                    {

                        ReaderConfig.locateData.LocateStartStop = "START";

                        ReaderConfig.locateData.LocateData = "0";

                        ReaderConfig.locateData.LocateTagID_ON = true;

                        ReaderConfig.isLocateRunning = false;

                    }

                    if ((ReaderConfig.isInventoryReadRunning == true) || (ReaderConfig.isInventoryRunning == true))

                    {

                        ReaderConfig.isInventoryRunning = false;

                        ReaderConfig.isInventoryReadRunning = false;

                        if (!ReaderConfig.isGetTagsData)

                            ReaderConfig.isInventoryScreenTagData = false;

                        ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";

                    }

                    ReaderConfig.isAbortComplete = true;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_Inventory.commandName.ToLower())

            {

                ReaderConfig.isCommandComplete = true;

                if (responseStatusMsg.Status.Equals("Inventory Started in Batch Mode"))

                {

                    ReaderConfig.isInventoryRunning = true;

                    ReaderConfig.isInventoryReadRunning = false;

                    ReaderConfig.BatchMode.isEnabled = true;

                }

                else if (!responseStatusMsg.Status.Equals("OK"))

                {

                    ReaderConfig.isInventoryRunning = false;

                    ReaderConfig.isInventoryReadRunning = false;

                    ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";

                }



            }

            else if (responseStatusMsg.command.Trim() == Command_LocateTag.commandName.ToLower())

            {

                ReaderConfig.isCommandComplete = true;

                if ((responseStatusMsg.Status != "OK"))

                {

                    ReaderConfig.locateData.LocateStartStop = "START";

                    ReaderConfig.locateData.LocateTagID_ON = true;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_Read.commandName.ToLower())

            {

                if (ReaderConfig.isInventoryReadRunning == true)

                {

                    ReaderConfig.isCommandComplete = true;

                    if (responseStatusMsg.Status != "OK")

                    {

                        ReaderConfig.isInventoryRunning = false;

                        ReaderConfig.isInventoryReadRunning = false;

                        ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";

                    }

                }

            }

            else if ((responseStatusMsg.command.Trim() == Command_ChangeConfig.commandName.ToLower()) ||

                (responseStatusMsg.command.Trim() == Command_SetRegulatory.commandName.ToLower()))

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isConfigSaved = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                    return;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_GetAllSupportedRegions.commandName.ToLower())

            {

                ReaderConfig.isGetAllRegionsComplete = true;

                return;

            }

            else if (responseStatusMsg.command.Trim() == Command_SetAntennaConfiguration.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isAntennaSetComplete = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_SetQueryParams.commandName.ToLower())

            {

                if (ReaderConfig.onAccessScreen == true)

                {

                    return;

                }



                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isSingulationSetComplete = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                }

            }

            else if ((responseStatusMsg.command.Trim() == Command_SetStartTrigger.commandName.ToLower()) ||

                (responseStatusMsg.command.Trim() == Command_SetStopTrigger.commandName.ToLower()))

            {

                ReaderConfig.isStartStopSetComplete = true;

                if (responseStatusMsg.Status == "OK")

                {

                    if (ReaderConfig.onAccessScreen == false)

                    {

                        ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                        ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                        await Task.Delay(1000);

                        ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                    }

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_SetReportConfig.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isTagReportSetComplete = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    if (ReaderConfig.SettingsStaus.SettingsStatusShow == false)

                    {

                        ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                        await Task.Delay(1000);

                        ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                    }

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_SetAttr.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    if (ReaderConfig.SettingsStaus.SettingsStatusShow == false)

                    {

                        ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                        await Task.Delay(1000);

                        ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                    }

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_SetDynamicPower.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isDPOSetComplete = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_SetSelectRecords.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "OK")

                {

                    ReaderConfig.isPreFilterSetComplete = true;

                    ReaderConfig.SettingsStaus.SettingsStatus = "Settings Applied Successfully";

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                }

            }

            else if (responseStatusMsg.command.Trim() == Command_Connect.commandName.ToLower())

            {

                if (responseStatusMsg.Status == "Connection Successful")

                {

                    ReaderConfig.isConnectWithPasswordEnabled = false;

                    ReaderConfig.isConnectComplete = true;

                }

                else if (responseStatusMsg.Status.Trim().ToLower() == "password mismatch error")

                {

                    ReaderConfig.isConnectWithPasswordEnabled = true;

                    ReaderConfig.isConnectComplete = true;

                }

                return;

            }

            else if (responseStatusMsg.command.Trim() == Command_SetAccessCriteria.commandName.ToLower())

            {

                if (ReaderConfig.onAccessScreen == true)

                {

                    return;

                }

            }



            if (responseStatusMsg.Status != "OK")

            {

                if (ReaderConfig.onAccessScreen == true)

                {

                    ReaderConfig.accessTagData.RecievedStatus = responseStatusMsg.Status;

                    ReaderConfig.isAccessComplete = true;

                }

                else

                {

                    ReaderConfig.SettingsStaus.SettingsStatus = responseStatusMsg.Status;

                    ReaderConfig.SettingsStaus.SettingsStatusShow = true;

                    await Task.Delay(1000);

                    ReaderConfig.SettingsStaus.SettingsStatusShow = false;

                }

            }

        }



        /* Summary for: showStatus

            Displays all the error messages/status(if required) in a MessageDialog

           Input : commandName=> name of the command , Status=> error/status to be displayed

           Output : none            

         */

        public void showStatus(String commandName, string Status)

        {

            MainPage rootPage = MainPage.Current;

            rootPage.ShowStatus(commandName.ToUpper().Trim() + " : \r\n", Status);

        }



        /* Summary for: notificationFromReader

           1) Handles all notification messages and maintains all neceassary internal states           

          Input : msg=> notification msg(type:IMsg)

          Output : none            

        */

        public void notificationFromReader(IMsg msg)

        {

            readerobj = ReaderConnect.getInstance();

            if (msg is Notification_TriggerEvent) // handles handheld/immediate trigger cases

            {

                Notification_TriggerEvent triggerNotification = (Notification_TriggerEvent)msg;

                if (triggerNotification.TriggerValue == ENUM_TRIGGER_ID.TRIGGER_PRESS)

                {

                    //check if start trgiggers are immediate

                    if ((ReaderConfig.startTriggerParams.IgnoreHandHeldTrigger == true) && (ReaderConfig.startTriggerParams.Repeat == false))

                    {

                        if ((ReaderConfig.isInventoryRunning == false) && (ReaderConfig.isInventoryReadRunning == false))

                            startInventory();

                        if ((ReaderConfig.isLocateRunning == false) && (ReaderConfig.onTagLocateScreen == true))

                        {

                            Command_LocateTag locateTag = new Command_LocateTag();

                            locateTag.epc = (byte[])ASCIIUtil.ParseArrayFromString(ReaderConfig.selectedTagEPC.SelectedTag.Trim(), "byteArray", "HEX");

                            readerobj.writeData(locateTag.ToString());

                            ReaderConfig.isLocateRunning = true;

                            ReaderConfig.locateData.LocateStartStop = "STOP";

                        }



                    }

                }

                if (triggerNotification.TriggerValue == ENUM_TRIGGER_ID.TRIGGER_RELEASE)

                {

                    //check if stop trgiggers are immediate

                    if ((ReaderConfig.stopTriggerParams.IgnoreHandHeldTrigger) && (ReaderConfig.stopTriggerParams.DisableStopOnAccessCount)

                && (ReaderConfig.stopTriggerParams.DisableStoponInventoryCount) && (ReaderConfig.stopTriggerParams.DisableStopOntagcount)

                && (ReaderConfig.stopTriggerParams.DisableStopOnTimeout))

                    {

                        if ((ReaderConfig.isInventoryRunning == true) || (ReaderConfig.isInventoryReadRunning == true))

                        {

                            abortOperation();

                        }

                        if (ReaderConfig.isLocateRunning == true)

                        {

                            Command_abort abortCmd = new Command_abort();

                            readerobj.writeData(abortCmd.ToString());

                        }

                    }

                }

            }

            else if (msg is Notification_StartOperation)

            {

                if (ReaderConfig.startTriggerParams.Repeat == true && !ReaderConfig.isLocateRunning)

                {

                    Startinventory_timer(true, true);

                }

            }

            else if (msg is Notification_StopOperation)// handle triggers except handheld

            {

                if (ReaderConfig.startTriggerParams.Repeat == false)

                {

                    if (ReaderConfig.BatchMode.isEnabled)

                    {

                        Startinventory_timer(false, false);

                        getTagsOperation();

                    }

                    else

                    {

                        ReaderConfig.isInventoryRunning = false;

                        ReaderConfig.isInventoryScreenTagData = false;

                        ReaderConfig.StartStopButtonStatus.STARTSTATUS = "START";

                        if (!ReaderConfig.isGetTagsData)

                            Startinventory_timer(false, true);



                        if (ReaderConfig.connectionConfig.exportData)

                        {

                            exportData();

                        }

                    }

                }

                else if (!ReaderConfig.isGetTagsData) //use stop notification for time stop in between the inventory periodic with delay

                {

                    Startinventory_timer(false, true);

                }

                if (ReaderConfig.onAccessScreen)

                    ReaderConfig.isAccessComplete = true;

            }

            else if (msg is Notification_OperEndSummary)

            {



            }

            else if (msg is Notification_BatchModeEvent)

            {

                Notification_BatchModeEvent batchmodeNotifcation = (Notification_BatchModeEvent)msg;

                if (ReaderConfig.isInitialSettingsRecieved == false)

                    ReaderConfig.inventoryRawData.Clear();

                ReaderConfig.isBatchModeEventRecieved = true;

                ReaderConfig.BatchMode.isEnabled = true;

                ReaderConfig.startTriggerParams.Repeat = batchmodeNotifcation.Repeat == 1 ? true : false;

                {

                    ReaderConfig.isInventoryRunning = true;

                    ReaderConfig.StartStopButtonStatus.STARTSTATUS = "STOP";

                    ReaderConfig.DeviceSerial = "Running in Batch Mode";

                    readerobj.items[ReaderConfig.connectedReaderIndex].SerialDisplayName = ReaderConfig.DeviceSerial;

                    ReaderConfig.DeviceModel = "Running in Batch Mode";

                    readerobj.items[ReaderConfig.connectedReaderIndex].ModelDisplayName = ReaderConfig.DeviceModel;

                }

            }

            else if (msg is Notification_BatteryEvent)

            {

                int imagenum = 0;

                Notification_BatteryEvent batteryEvent = (Notification_BatteryEvent)msg;

                ReaderConfig.batteryLevel.BatteryLevel = String.Format("{0}%", batteryEvent.Level);

                imagenum = (batteryEvent.Level / 10) + 1;

                if (imagenum > 10)

                    imagenum = 10;

                Uri imageURI = new Uri("ms-appx:///Assets/battery_" + imagenum.ToString() + ".png", UriKind.Absolute);

                BitmapImage batteryImage = new BitmapImage(imageURI);

                ReaderConfig.batteryLevel.BatteryImage = batteryImage;

                ReaderConfig.batteryLevel.BatteryStatus = "Status: Discharging";



                if (!batteryEvent.Cause.Equals("User Request"))

                {

                    ReaderConfig.batteryLevel.BatteryStatus = "Status: " + batteryEvent.Cause + "!";

                    if (ReaderConfig.connectionConfig.readerBatteryStatus)

                    {

                        if (MainPage.isApplicationWindowActive)

                            showStatus("Battery Notification", batteryEvent.Cause);

                        else

                        {

                            var settings = ApplicationData.Current.LocalSettings;

                            settings.Values["Battery Notification"] = batteryEvent.Cause;

                        }

                    }

                }



                if (batteryEvent.Charging == true)

                {

                    ReaderConfig.batteryLevel.BatteryStatus = "Status: Charging";

                }

                string imageIdentifier = "battery";

                if (ReaderConfig.isDynmaicPowerEnabled)

                    imageIdentifier = "dpo";

                if (batteryEvent.Level <= 25)

                    imageURI = new Uri("ms-appx:///Assets/" + imageIdentifier + "_0_25.png", UriKind.Absolute);

                else if (batteryEvent.Level <= 50)

                    imageURI = new Uri("ms-appx:///Assets/" + imageIdentifier + "_25_50.png", UriKind.Absolute);

                else if (batteryEvent.Level <= 75)

                    imageURI = new Uri("ms-appx:///Assets/" + imageIdentifier + "_50_75.png", UriKind.Absolute);

                else

                    imageURI = new Uri("ms-appx:///Assets/" + imageIdentifier + "_75_100.png", UriKind.Absolute);

                ReaderConfig.batteryDPO.BatteryDPOImage = new BitmapImage(imageURI);

            }

            else if (msg is Notification_PowerEvent)

            {

                Notification_PowerEvent powerEvent = (Notification_PowerEvent)msg;

                showStatus("Power Notification ", powerEvent.Cause.ToString());

            }

            else if (msg is Notification_TemperatureEvent)

            {

                Notification_TemperatureEvent temperatureEvent = (Notification_TemperatureEvent)msg;

                showStatus("Temperature Notification ", temperatureEvent.Cause.ToString());

            }

        }



        /* Summary for: handleAccessData

           1) Handles tagdata for access screen

           2) Binds the data to access screen elements

          Input : response_tagData=> tagdata from the reader

          Output : none            

        */

        public void handleAccessData(Response_TagData response_tagData)

        {

            if (ReaderConfig.onAccessScreen == false)

                return;

            if (response_tagData.tagAcessOprations[0].opration.Trim().ToString().ToLower() == "read")

            {

                if (response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower() == "ok")

                {

                    ReaderConfig.accessTagData.RecievedData = response_tagData.tagAcessOprations[0].memoryBankData;

                    ReaderConfig.accessTagData.RecievedStatus = "Operation Successful";

                }

                else

                {

                    ReaderConfig.accessTagData.RecievedStatus = response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower();

                    //showStatus(response_tagData.tagAcessOprations[0].opration,

                    //    response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower());

                }

            }

            if ((response_tagData.tagAcessOprations[0].opration.Trim().ToString().ToLower() == "write") ||

                (response_tagData.tagAcessOprations[0].opration.Trim().ToString().ToLower() == "lock") ||

                 (response_tagData.tagAcessOprations[0].opration.Trim().ToString().ToLower() == "kill"))

            {

                if (response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower() != "ok")

                {

                    //showStatus(response_tagData.tagAcessOprations[0].opration,

                    //  response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower());

                    ReaderConfig.accessTagData.RecievedStatus = response_tagData.tagAcessOprations[0].operationStatus.Trim().ToString().ToLower();

                }

                else

                    ReaderConfig.accessTagData.RecievedStatus = "Operation Successful";

            }

            ReaderConfig.isAccessComplete = true;

        }



        /* Summary for: handleInventortyData

           1) Handles tagdata for invetory screen

           2) Binds the data to inventory screen elements

          Input : response_tagData=> tagdata from the reader

          Output : none            

        */

        public void handleInventortyData(Response_TagData response_tagData)

        {

            bool addnew = false;

            if (ReaderConfig.inventoryRawData.Count > 0) // if it is not the first item to be added to the list

            {

                var found = ReaderConfig.inventoryRawData.FirstOrDefault(c => c.EPCID == response_tagData.EPCId);

                if (found != null)  // if item is not in the display list

                {

                    found.Count = found.Count + 1;

                }

                else  // if item is already in the display list

                {

                    addnew = true;

                    ReaderConfig.TagsRead.UniqueCount = ReaderConfig.TagsRead.UniqueCount + 1;



                }



                if (ReaderConfig.isGetTagsData == true)

                    ReaderConfig.TagsRead.ReadTags = ReaderConfig.TagsRead.ReadTags +

                        ((response_tagData.TagSeenCount == null) ? 1 : Convert.ToInt32(response_tagData.TagSeenCount));

                else

                    ReaderConfig.TagsRead.ReadTags = ReaderConfig.TagsRead.ReadTags + 1;

            }

            else  // if it is the first item to be added to the list

            {

                addnew = true;

                if (ReaderConfig.isGetTagsData == true)

                    ReaderConfig.TagsRead.ReadTags = (response_tagData.TagSeenCount == null) ? 1 : Convert.ToInt32(response_tagData.TagSeenCount);

                else

                    ReaderConfig.TagsRead.ReadTags = 1;

                ReaderConfig.TagsRead.UniqueCount = 1;

            }



            if (addnew == true)

            {

                if (ReaderConfig.isGetTagsData == true)

                {

                    ReaderConfig.inventoryRawData.Add(new inventoryData

                    {

                        EPCID = response_tagData.EPCId,

                        Count = (response_tagData.TagSeenCount == null) ? 1 : Convert.ToInt32(response_tagData.TagSeenCount),

                        Visible = "Collapsed",



                        PC = (response_tagData.PC == null) ? "" : response_tagData.PC, //check if the field is null

                        PCVisible = (response_tagData.PC == null) ? "Collapsed" : "Visible",



                        Channel = (response_tagData.ChannelIndex == null) ? "" : response_tagData.ChannelIndex,

                        ChannelVisible = (response_tagData.ChannelIndex == null) ? "Collapsed" : "Visible",



                        RSSI = (response_tagData.RSSI == null) ? "" : response_tagData.RSSI,

                        RSSIVisible = (response_tagData.RSSI == null) ? "Collapsed" : "Visible",



                        Phase = (response_tagData.Phase == null) ? "" : response_tagData.Phase,

                        PhaseVisible = (response_tagData.Phase == null) ? "Collapsed" : "Visible",



                        AccessData = null,

                        AccessDataVisible = "Collapsed",



                    });

                }

                else

                {

                    if ((ReaderConfig.isInventoryRunning == true) && (ReaderConfig.isInventoryReadRunning == false))

                    {

                        ReaderConfig.inventoryRawData.Add(new inventoryData

                        {

                            EPCID = response_tagData.EPCId,

                            Count = 1,

                            Visible = "Collapsed",



                            PC = (response_tagData.PC == null) ? "" : response_tagData.PC, //check if the field is null

                            PCVisible = (response_tagData.PC == null) ? "Collapsed" : "Visible",



                            Channel = (response_tagData.ChannelIndex == null) ? "" : response_tagData.ChannelIndex,

                            ChannelVisible = (response_tagData.ChannelIndex == null) ? "Collapsed" : "Visible",



                            RSSI = (response_tagData.RSSI == null) ? "" : response_tagData.RSSI,

                            RSSIVisible = (response_tagData.RSSI == null) ? "Collapsed" : "Visible",



                            Phase = (response_tagData.Phase == null) ? "" : response_tagData.Phase,

                            PhaseVisible = (response_tagData.Phase == null) ? "Collapsed" : "Visible",



                            AccessData = null,

                            AccessDataVisible = "Collapsed",



                        });

                    }

                    if ((ReaderConfig.isInventoryRunning == false) && (ReaderConfig.isInventoryReadRunning == true))

                    {

                        if ((response_tagData.tagAcessOprations[0].memoryBankData == null))

                        {

                            ReaderConfig.TagsRead.ReadTags--;

                            ReaderConfig.TagsRead.UniqueCount--;

                            return;

                        }



                        ReaderConfig.inventoryRawData.Add(new inventoryData

                        {

                            EPCID = response_tagData.EPCId,

                            Count = 1,

                            Visible = "Collapsed",



                            PC = (response_tagData.PC == null) ? "" : response_tagData.PC, //check if the field is null

                            PCVisible = (response_tagData.PC == null) ? "Collapsed" : "Visible",



                            Channel = (response_tagData.ChannelIndex == null) ? "" : response_tagData.ChannelIndex,

                            ChannelVisible = (response_tagData.ChannelIndex == null) ? "Collapsed" : "Visible",



                            RSSI = (response_tagData.RSSI == null) ? "" : response_tagData.RSSI,

                            RSSIVisible = (response_tagData.RSSI == null) ? "Collapsed" : "Visible",



                            Phase = (response_tagData.Phase == null) ? "" : response_tagData.Phase,

                            PhaseVisible = (response_tagData.Phase == null) ? "Collapsed" : "Visible",



                            AccessData = (response_tagData.tagAcessOprations[0].memoryBankData == null) ? "" : response_tagData.tagAcessOprations[0].memoryBankData,

                            AccessDataVisible = (response_tagData.tagAcessOprations[0].memoryBankData == null) ? "Collapsed" : "Visible",

                            AccessDataLabel = response_tagData.tagAcessOprations[0].memoryBank.ToUpper(),

                        });

                    }

                }

            }

        }



        internal async Task<bool> isCommandComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isCommandComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return ReaderConfig.isCommandComplete;

        }



        /* Summary for: isConfigSaved

           1) checks if the saveconfig response was recieved from the reader

          Input : none

          Output : none            

        */

        public async Task<bool> isConfigSaved()

        {

            int Count = TIME_OUT_COUNT * 2;

            while (ReaderConfig.isConfigSaved == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isAntennaConfigCompltete

         1) checks if the AntennaConfigCompltete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isAntennaConfigSetCompltete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isAntennaSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isQueryConfigSetCompltete

         1) checks if the QueryConfigSetCompltete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isQueryConfigSetCompltete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isSingulationSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isStartStopConfigSetCompltete

         1) checks if the Start/StopConfigSetCompltete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isStartStopConfigSetCompltete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isStartStopSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return ReaderConfig.isStartStopSetComplete;

        }



        public async Task<bool> isAccessComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isAccessComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return ReaderConfig.isAccessComplete;

        }



        /* Summary for: isDPOConfigSetCompltete

         1) checks if the DPOConfigSetCompltete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isDPOConfigSetCompltete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isDPOSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isTagReportConfigSetCompltete

         1) checks if the TagReportConfigSetCompltete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isTagReportConfigSetCompltete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isTagReportSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isPreFilterConfigSetComplete

         1) checks if the PreFilterConfigSetComplete response was recieved from the reader

        Input : none

        Output : none            

       */

        public async Task<bool> isPreFilterConfigSetComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isPreFilterSetComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isGetAllRegionsComplete

           1) checks if GetAllSupportedRegion response was recieved from the reader

           2) needed to start getting the region details of all regions returned by getGetAllSupportedRegion

          Input : none

          Output : none            

        */

        public async Task<bool> isGetAllRegionsComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isGetAllRegionsComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isAbortComplete

          1) checks if isAbortComplete response was recieved from the reader

         Input : none

         Output : none            

       */

        public async Task<bool> isAbortComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isAbortComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isConnectComplete

          1) checks if Connect response was recieved from the reader

         Input : none

         Output : none            

       */

        public async Task<bool> isConnectComplete()

        {

            int Count = TIME_OUT_COUNT * 2;

            while (ReaderConfig.isConnectComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isGetAllRegionInfoComplete

          1) checks if get reion for last region response was recieved from the reader

         Input : none

         Output : none            

       */

        public async Task<bool> isGetAllRegionInfoComplete()

        {

            int Count = TIME_OUT_COUNT * 2;

            while (ReaderConfig.isGetAllRegionsInfoComplete == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return true;

        }



        /* Summary for: isInitialSettingsRecievedComplete

          1) checks if reader configuration is recieved from the reader

         Input : none

         Output : none            

        */

        public async Task<bool> isInitialSettingsRecievedComplete()

        {

            int Count = TIME_OUT_COUNT;

            while (ReaderConfig.isInitialSettingsRecieved == false && Count > 0)

            {

                await Task.Delay(100);

                Count--;

            }

            return ReaderConfig.isInitialSettingsRecieved;

        }



        /* Summary for: startInventory

           1) Sends the inventory command and maintains invetory flags        

          Input : none

          Output : none            

        */

        public void startInventory()

        {

            if ((ReaderConfig.onRapidReadScreen == true) || (ReaderConfig.onInventoryScreen == true))

            {

                ReaderConfig.isInventoryScreenTagData = true;

                ReaderConfig.inventoryRawData.Clear();

                ReaderConfig.TagsRead.UniqueCount = 0;

                ReaderConfig.TagsRead.ReadTags = 0;

                ReaderConfig.StartStopButtonStatus.STARTSTATUS = "STOP";



                if ((ReaderConfig.bankSelectedAtInventory != 0) && (ReaderConfig.onInventoryScreen == true))

                {

                    startReadInventoryScreen();

                    return;

                }



                // If enable unique tag report, need purge (reset) NGE database before inventory

                if (ReaderConfig.reportUniqueTags)

                {

                    readerobj.writeData(new Command_PurgeTags().ToString());

                }



                readerobj = ReaderConnect.getInstance();

                Command_Inventory inventoryObj = new Command_Inventory();

                if (ReaderConfig.isSelectRecordSet == true)

                {

                    inventoryObj.AccessConfig = new Param_AccessConfig();

                    inventoryObj.AccessConfig.DoSelect = true;

                }



                readerobj.writeData(inventoryObj.ToString());

                ReaderConfig.bankSelectedAtInventory = 0;

                ReaderConfig.isInventoryRunning = true;

                ReaderConfig.isInventoryReadRunning = false;

                Startinventory_timer(true, false);//reset timer

                //check if start trgiggers are immediate               

                if (!((ReaderConfig.startTriggerParams.IgnoreHandHeldTrigger == true) && (ReaderConfig.startTriggerParams.Repeat == false)))

                {

                    Startinventory_timer(false, true);

                }

            }

        }



        /* Summary for: startReadInventoryScreen

          1) Sends the read command  and maintains inventory/read flags        

         Input : none

         Output : none            

       */

        public void startReadInventoryScreen()

        {

            Command_Read readobj = new Command_Read();

            switch (ReaderConfig.bankSelectedAtInventory)

            {

                case 1:

                    readobj.Bank = ENUM_MEMORY_BANK.EPC;

                    break;

                case 2:

                    readobj.Bank = ENUM_MEMORY_BANK.RESV;

                    break;

                case 3:

                    readobj.Bank = ENUM_MEMORY_BANK.TID;

                    break;

                case 4:

                    readobj.Bank = ENUM_MEMORY_BANK.USER;

                    break;

            }

            if (ReaderConfig.isSelectRecordSet == true)

            {

                readobj.AccessConfig = new Param_AccessConfig();

                readobj.AccessConfig.DoSelect = true;

            }



            readerobj = ReaderConnect.getInstance();

            readobj.ReportConfig = ReaderConfig.reportConfigParams.ReportConfig;

            readerobj.writeData(readobj.ToString());

            ReaderConfig.isInventoryRunning = false;

            ReaderConfig.isInventoryReadRunning = true;

            Startinventory_timer(true, false); // resetTimer

            //check if start trgiggers are immediate

            if (!((ReaderConfig.startTriggerParams.IgnoreHandHeldTrigger == true) && (ReaderConfig.startTriggerParams.Repeat == false)))

            {

                Startinventory_timer(false, true);

            }

        }



        /* Summary for: abortOperation

          1) Sends the abort command  and maintains inventory/read flags        

         Input : none

         Output : none            

       */

        public async void abortOperation()

        {

            if (ReaderConfig.isReaderConnected == false)

            {

                showStatus(Command_abort.commandName, "No active connection with reader");

                return;

            }

            if ((ReaderConfig.onRapidReadScreen == true) || (ReaderConfig.onInventoryScreen == true))

            {

                Command_abort abortobj = new Command_abort();

                readerobj = ReaderConnect.getInstance();

                readerobj.writeData(abortobj.ToString());

                ReaderConfig.isAbortComplete = false;

                Startinventory_timer(false, false);

                await isAbortComplete();

                //if((genXConfig.batchmode==2)||(genXConfig.isInitialSettingsRecieved==false))

                if (ReaderConfig.BatchMode.isEnabled && ReaderConfig.startTriggerParams.Repeat)

                {

                    Startinventory_timer(false, false);

                    getTagsOperation();

                }

            }

        }



        /* Summary for: getTagsOperation

          1) Sends the gettags command       

         Input : none

         Output : none            

       */

        public void getTagsOperation()

        {

            Command_GetTags gettags = new Command_GetTags();

            readerobj.writeData(gettags.ToString());

            ReaderConfig.isInventoryScreenTagData = true;

            ReaderConfig.isGetTagsData = true;

            ReaderConfig.isBatchModeEventRecieved = false;

            ReaderConfig.BatchMode.isEnabled = false;

        }



        /* Summary for: Startinventory_timer

          1) Starts the timer needed for readrate calculations        

         Input : start(type:bool)=> if true, start timer, else stop timer

         Output : none            

       */

        DispatcherTimer timer = new DispatcherTimer();

        TimeSpan ReadTime = new TimeSpan(0, 0, 1);

        TimeSpan ReadTimeReset = new TimeSpan(0, 0, 0);

        // wait for 50*100ms = 5 Seconds

        private readonly int TIME_OUT_COUNT = 50;



        public void Startinventory_timer(bool start, bool pause) // start=true, pause=true => come back from pause(resume) , start=true, pause=false => start

        {                                                        // start=false, pause=true => pause  ,start=false, pause=false => stop                     

            if (start)

            {

                timer.Tick += inventory_timer_Tick;

                timer.Interval = new TimeSpan(0, 0, 1);

                timer.Start();

                if (pause)

                {

                    ReaderConfig.inventoryReadRate.ReadTime = ReadTimeReset + ReaderConfig.ReadTimeToAdd;

                }

                else

                {

                    ReaderConfig.inventoryReadRate.ReadRate = 0;

                    ReaderConfig.inventoryReadRate.ReadTime = ReadTimeReset;

                }

            }

            else

            {

                timer.Stop();

                timer.Tick -= inventory_timer_Tick;

                if (pause)

                {

                    ReaderConfig.ReadTimeToAdd = ReaderConfig.inventoryReadRate.ReadTime;

                }

                //genXConfig.inventoryReadRate.ReadTime = genXConfig.inventoryReadRate.ReadTime.Add(ReadTime);

                int seconds = (int)ReaderConfig.inventoryReadRate.ReadTime.TotalSeconds;

                if (seconds > 0)

                    ReaderConfig.inventoryReadRate.ReadRate = ReaderConfig.TagsRead.ReadTags / seconds;

            }

        }

        void inventory_timer_Tick(object sender, object e)

        {

            ReaderConfig.inventoryReadRate.ReadTime = ReaderConfig.inventoryReadRate.ReadTime.Add(ReadTime);

            int seconds = (int)ReaderConfig.inventoryReadRate.ReadTime.TotalSeconds;

            if (seconds > 0)

                ReaderConfig.inventoryReadRate.ReadRate = ReaderConfig.TagsRead.ReadTags / seconds;

        }





        /* Summary for: exportData

            Export tag data to external SD card

           Output : none            

         */

        public async void exportData()

        {

            try

            {

                ObservableCollection<inventoryData> inventoryExportData = new ObservableCollection<inventoryData>(ReaderConfig.inventoryRawData);

                String strUniqueCount = ReaderConfig.TagsRead.UniqueCount.ToString();

                String strReadTags = ReaderConfig.TagsRead.ReadTags.ToString();

                String strReadTime = ReaderConfig.inventoryReadRate.ReadTime.ToString("g");





                // Get the logical root folder for all external storage devices.

                StorageFolder externalDevices = KnownFolders.RemovableDevices;



                // Get the first child folder, which represents the SD card.

                StorageFolder sdCard = (await externalDevices.GetFoldersAsync()).FirstOrDefault();



                // access inventory folder

                StorageFolder inventoryFolder = null;

                try

                {

                    inventoryFolder = await sdCard.GetFolderAsync("inventory");

                }

                catch (Exception e)

                {

                    System.Diagnostics.Debug.WriteLine("Create directory 'inventory' due to not exist");

                    inventoryFolder = await sdCard.CreateFolderAsync("inventory", CreationCollisionOption.FailIfExists);

                }



                // create file name

                string temp = DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss.fff");



                StorageFile dataFile = await inventoryFolder.CreateFileAsync("RFD8500" + ReaderConfig.DeviceSerial + "_" + temp + ".csv", CreationCollisionOption.ReplaceExisting);

                var stream = await dataFile.OpenAsync(FileAccessMode.ReadWrite);



                using (var outputStream = stream.GetOutputStreamAt(0))

                {

                    using (var dataWriter = new Windows.Storage.Streams.DataWriter(outputStream))

                    {

                        dataWriter.WriteString("INVENTORY SUMMARY" + "\n");

                        dataWriter.WriteString("UNIQUE COUNT:," + strUniqueCount + "\n");

                        dataWriter.WriteString("TOTAL COUNT:," + strReadTags + "\n");

                        dataWriter.WriteString("READ TIME:," + strReadTime + "\n\n");

                        dataWriter.WriteString("TAG ID,COUNT" + "\n");



                        foreach (inventoryData tag in inventoryExportData)

                        {

                            dataWriter.WriteString(tag.EPCID.ToString() + "," + tag.Count.ToString() + "\n");

                        }



                        await dataWriter.StoreAsync();

                        await outputStream.FlushAsync();

                    }

                }



                stream.Dispose();



            }

            catch (Exception e)

            {

                string str = e.Message;

                System.Diagnostics.Debug.WriteLine(str);

            }

        }



    }

}

