#define PICKER_VIEW_BANK        0
#define PICKER_VIEW_OFFSET      1
#define PICKER_VIEW_LENGTH      2
#define PICKER_VIEW_POWER_GAIN  3

#define ALERT_VIEW_PASSWORD         0
#define ALERT_VIEW_OPERATION_TIME   1
#define ALERT_VIEW_READING          2

#define ALERT_VIEW_OUTHERVIEW       30

#define MSG_TAG_WAIT        @"Tag memory to read or erase\nPlease click the button."

#import "ReadMemoryViewController.h"
#import "AppDelegate.h"
#import "UserData.h"
#import "SystemSetting.h"
@interface ReadMemoryViewController () {
    AppDelegate *appDelegate;
    UIAlertView *currentAlertView;
    BOOL isActionResult;
    MaskType maskType;
    SystemSetting * systemSetting;
}
@property (weak, nonatomic) IBOutlet UILabel *selectionTagLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UILabel *address1Label;
@property (weak, nonatomic) IBOutlet UILabel *address2Label;
@property (weak, nonatomic) IBOutlet UILabel *address3Label;
@property (weak, nonatomic) IBOutlet UILabel *address4Label;
@property (weak, nonatomic) IBOutlet UILabel *address5Label;
@property (weak, nonatomic) IBOutlet UILabel *address6Label;
@property (weak, nonatomic) IBOutlet UILabel *address7Label;
@property (weak, nonatomic) IBOutlet UILabel *address8Label;
@property (weak, nonatomic) IBOutlet UILabel *value1Label;
@property (weak, nonatomic) IBOutlet UILabel *value2Label;
@property (weak, nonatomic) IBOutlet UILabel *value3Label;
@property (weak, nonatomic) IBOutlet UILabel *value4Label;
@property (weak, nonatomic) IBOutlet UILabel *value5Label;
@property (weak, nonatomic) IBOutlet UILabel *value6Label;
@property (weak, nonatomic) IBOutlet UILabel *value7Label;
@property (weak, nonatomic) IBOutlet UILabel *value8Label;
@property (weak, nonatomic) IBOutlet UITextField *bankTextField;
@property (weak, nonatomic) IBOutlet UITextField *offsetTextField;
@property (weak, nonatomic) IBOutlet UITextField *lengthTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *powerGainTextField;
@property (weak, nonatomic) IBOutlet UITextField *operationTimeTextField;
@property (weak, nonatomic) IBOutlet UIButton *readBtn;
@property (weak, nonatomic) IBOutlet UIButton *blockEraseBtn;
@property (weak, nonatomic) IBOutlet UIButton *clearBtn;
@property (weak, nonatomic) IBOutlet UIButton *maskBtn;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIView *bankPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *offsetPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *lengthPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *powerGainPickerTopView;
@property (weak, nonatomic) IBOutlet UILabel *rssiLabel;
@property (weak, nonatomic) IBOutlet UILabel *phaseLabel;
@property (weak, nonatomic) IBOutlet UISwitch *reportRssiSwitch;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *reportRssiCollection;
@property (strong, nonatomic) NSArray *bankPickerData;
@property (strong, nonatomic) NSArray *offsetPickerData;
@property (strong, nonatomic) NSArray *lengthPickerData;
@property (strong, nonatomic) NSArray *bitData;
@property (strong, nonatomic) NSArray *wordData;
@property (strong, nonatomic) NSArray *powerGainPickerData;
@property (readwrite, nonatomic) NSInteger offsetValue;
@property (readwrite, nonatomic) NSInteger lengthValue;

@end

@implementation ReadMemoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    systemSetting = [SystemSetting sharedSystemSetting];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    [center addObserver:self selector:@selector(AsReaderGUNConnected:) name:@"AsReaderGUNConnected" object:nil];
    [appDelegate.mReader setDelegate:self];
}
- (void)viewDidAppear:(BOOL)animated{
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    if (appDelegate.mReader == nil) {
        return;
    }
    
    [self initPowerGainPickerData];
    
    int nPower = appDelegate.mReader.powerGain;
    NSInteger operationTime = appDelegate.mReader.operationTime;
    
    appDelegate.mReader.continuousMode = NO;
    BOOL isReportRSSI = appDelegate.mReader.rssiMode;
    maskType = appDelegate.mReader.maskTypeValue;
    if (_maskValue != nil) {
        [appDelegate initMask:_maskValue maskType:MaskType_Selection];
    }
    
    isActionResult = NO;
    
    [self setPowerGain:(int)(nPower / 10)];
    [self setOperationTime:[NSString stringWithFormat:@"%ld", (long)operationTime]];
    [self setBank:1];
    [self setOffset:2];
    [self setLength:2];
    [self setReportRssiModeEnabled:isReportRSSI];
    [self.pickerView reloadAllComponents];
    
    if (_maskValue != nil) {
        self.selectionTagLabel.text = _maskValue;
        self.maskBtn.enabled = NO;
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNConnected" object:nil];
    if (_maskValue != nil) {
        [appDelegate exitMask];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

#pragma mark - Storyboard Segue
-(IBAction)prepareForUnwind:(UIStoryboardSegue *)segue {
}

#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_BANK) {
        return self.bankPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_OFFSET) {
        return self.bitData.count;
    } else if (pickerView.tag == PICKER_VIEW_LENGTH) {
        return self.lengthPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_POWER_GAIN) {
        return self.powerGainPickerData.count;
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_BANK) {
        return [self.bankPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_OFFSET) {
        return [self.offsetPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_LENGTH) {
        return [self.lengthPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_POWER_GAIN) {
        return [self.powerGainPickerData objectAtIndex:row];
    }
    return @"None";
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == ALERT_VIEW_PASSWORD) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            [self setPassword:value];
        }
    } else if (alertView.tag == ALERT_VIEW_OPERATION_TIME) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            if(value.length == 0){
                value = @"0";
            }
            [self setOperationTime:value];
            appDelegate.mReader.operationTime = [value intValue];
            [systemSetting setOperationTime:[value intValue]];
        }
    } else if (alertView.tag == ALERT_VIEW_READING) {
        [self stopAction];
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSUInteger textlen = [textField.text length] + [string length] - range.length;
    if (textlen > MAX_PASSWORD_LENGTH) {
        return NO;
    }
    
    NSCharacterSet* nonHex = [[NSCharacterSet
                               characterSetWithCharactersInString: @"0123456789ABCDEFabcdef"]
                              invertedSet];
    NSRange nonHexRange = [string rangeOfCharacterFromSet:nonHex];
    BOOL isHex = (nonHexRange.location == NSNotFound);
    
    if (isHex) {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = [newString uppercaseString];
    }
    return NO;
}

#pragma mark - Getters
- (NSArray *)bankPickerData {
    return DATA_BANK;
}

- (NSArray *)offsetPickerData {
    if (_offsetPickerData == nil) {
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        for (NSString *offset in self.wordData) {
            [tmpArray addObject:[NSString stringWithFormat:@"%@ WORD", offset]];
        }
        _offsetPickerData = tmpArray;
    }
    return _offsetPickerData;
}
- (NSArray *)lengthPickerData {
    if (_lengthPickerData == nil) {
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        for (NSString *offset in self.wordData) {
            [tmpArray addObject:[NSString stringWithFormat:@"%@ WORD", offset]];
        }
        _lengthPickerData = tmpArray;
    }
    return _lengthPickerData;
}

- (NSArray *)bitData {
    return DATA_BIT;
}

- (NSArray *)wordData {
    return DATA_WORD;
}

#pragma mark - Init
- (void)initPowerGainPickerData {
    if (_powerGainPickerData == nil) {
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        int min = appDelegate.mReader.powerGainRange.min;
        int max = appDelegate.mReader.powerGainRange.max;
        
        for (int i = min; i <= max; i += 10) {
            [tmpArray addObject:[NSString stringWithFormat:@"%i.0 dB", i / 10]];
        }
        _powerGainPickerData = tmpArray;
    }
}

#pragma mark - IBAction
- (IBAction)bankBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_BANK;
    [self.pickerView reloadAllComponents];
    
    if (![self.bankTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.bankPickerData indexOfObject:self.bankTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.bankPickerTopView.hidden = NO;
}

- (IBAction)offsetBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_OFFSET;
    [self.pickerView reloadAllComponents];
    
    if (![self.offsetTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.offsetPickerData indexOfObject:self.offsetTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.offsetPickerTopView.hidden = NO;
}

- (IBAction)lengthBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_LENGTH;
    [self.pickerView reloadAllComponents];
    
    if (![self.lengthTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.lengthPickerData indexOfObject:self.lengthTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.lengthPickerTopView.hidden = NO;
}

- (IBAction)passwordBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Password:" message:@"Please enter password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
    [alert textFieldAtIndex:0].delegate = self;
    alert.tag = ALERT_VIEW_PASSWORD;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}

- (IBAction)powerGainBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_POWER_GAIN;
    [self.pickerView reloadAllComponents];
    
    if (![self.powerGainTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.powerGainPickerData indexOfObject:self.powerGainTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.powerGainPickerTopView.hidden = NO;
}

- (IBAction)operationTimeBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Operation Time:" message:@"Please enter operation time.\n(ex: 30 ms)" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_OPERATION_TIME;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}

- (IBAction)reportRssiSwitchTapped:(id)sender {
    appDelegate.mReader.rssiMode = [self.reportRssiSwitch isOn];
    [systemSetting setRssiMode:[self.reportRssiSwitch isOn]];
    [self setReportRssiModeEnabled:[self.reportRssiSwitch isOn]];
}

- (IBAction)readBtnTapped:(id)sender {
    [self readAction];
}

- (IBAction)blockEraseBtnTapped:(id)sender {
    isActionResult = NO;
    
    self.messageLabel.text = @"Erasing tag memory.\nPlease wait…";
    
    appDelegate.mReader.operationTime = [self.operationTimeTextField.text intValue];
    [systemSetting setOperationTime:[self.operationTimeTextField.text intValue]];
    MemoryBank bank = (int)[self.bankPickerData indexOfObject:self.bankTextField.text];
    
    [appDelegate.mReader blockErase:bank offset:(int)self.offsetValue length:(int)self.lengthValue];
    
    [self clearBtnTapped:sender];
    
}

- (IBAction)clearBtnTapped:(id)sender {
    self.selectionTagLabel.text = @"Result";
    self.messageLabel.text = MSG_TAG_WAIT;
    
    self.address1Label.text = @"0 WORD";
    self.address2Label.text = @"1 WORD";
    self.address3Label.text = @"2 WORD";
    self.address4Label.text = @"3 WORD";
    self.address5Label.text = @"4 WORD";
    self.address6Label.text = @"5 WORD";
    self.address7Label.text = @"6 WORD";
    self.address8Label.text = @"7 WORD";
    
    self.value1Label.text = @"0000";
    self.value2Label.text = @"0000";
    self.value3Label.text = @"0000";
    self.value4Label.text = @"0000";
    self.value5Label.text = @"0000";
    self.value6Label.text = @"0000";
    self.value7Label.text = @"0000";
    self.value8Label.text = @"0000";
    
    self.rssiLabel.text = @"0.0 dB";
    self.phaseLabel.text = @"0.0˚";
}

- (IBAction)maskBtnTapped:(id)sender {
    if (maskType == MaskType_Selection) {
        [self performSegueWithIdentifier:@"SelectionMask" sender:self];
    } else  {
        [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
        currentAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Please choosing the Selection Mask type in the RFID Option menu." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        return;
    }
}

- (IBAction)pickerCloseBtnTapped:(id)sender {
    [self hidePickerView];
}

- (IBAction)bankPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setBank:idx];
    [self hidePickerView];
}
- (IBAction)offsetPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setOffset:idx];
    [self hidePickerView];
}

- (IBAction)lengthPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setLength:idx];
    [self hidePickerView];
}

- (IBAction)powerGainPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    idx += (appDelegate.mReader.powerGainRange.min / 10);
    [self setPowerGain:idx];
    appDelegate.mReader.powerGain = (int)idx * 10;
    [systemSetting setPowerGain:(int)idx * 10];
    [self hidePickerView];
}
#pragma mark - Custom
- (void)hidePickerView {
    self.bankPickerTopView.hidden = YES;
    self.offsetPickerTopView.hidden = YES;
    self.lengthPickerTopView.hidden = YES;
    self.powerGainPickerTopView.hidden = YES;
    self.pickerView.hidden = YES;
}

- (void)setBank:(NSInteger)index {
    self.bankTextField.text = [self.bankPickerData objectAtIndex:index];
}
- (void)setOffset:(NSInteger)index {
    self.offsetTextField.text = [self.offsetPickerData objectAtIndex:index];
    self.offsetValue = index;
}
- (void)setLength:(NSInteger)index {
    self.lengthTextField.text = [self.lengthPickerData objectAtIndex:index];
    self.lengthValue = index;
}
- (void)setPassword:(NSString *)password {
    self.passwordTextField.text = password;
}
- (void)setPowerGain:(NSInteger)power {
    NSString *value = [NSString stringWithFormat:@"%i.0 dB", power];
    NSInteger index = [self.powerGainPickerData indexOfObject:value];
    if ([self.powerGainPickerData count] >index) {
        self.powerGainTextField.text = [self.powerGainPickerData objectAtIndex:index];
    }}
- (void)setOperationTime:(NSString *)operationTime {
    self.operationTimeTextField.text = operationTime;
}

- (void)readAction {
    isActionResult = NO;
    
    self.messageLabel.text = @"Reading tag memory.\nPlease wait…";
    
    appDelegate.mReader.operationTime = [self.operationTimeTextField.text intValue];
    [systemSetting setOperationTime:[self.operationTimeTextField.text intValue]];
    MemoryBank bank = (int)[self.bankPickerData indexOfObject:self.bankTextField.text];
    
    NSString *password = self.passwordTextField.text;
    
    [appDelegate.mReader setAccessPassword:password];
    
    [appDelegate.mReader readMemory:bank offset:(int)self.offsetValue length:(int)self.lengthValue];
    [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
    currentAlertView = [[UIAlertView alloc] initWithTitle:@"Please wait..." message:@"Reading tag memory" delegate:self cancelButtonTitle:@"Stop" otherButtonTitles:nil];
    currentAlertView.tag = ALERT_VIEW_READING;
    [currentAlertView show];
}

- (void)stopAction {
    [appDelegate.mReader stop];
}

- (void)setReportRssiModeEnabled:(BOOL)enabled {
    for(UILabel *elem in self.reportRssiCollection) {
        [elem setEnabled:enabled];
    }
    
    if (enabled == NO) {
        [self setReportRssiModeDefault];
    }
    
    [self.reportRssiSwitch setOn:enabled];
}

- (void)setReportRssiModeDefault {
    self.rssiLabel.text = [NSString stringWithFormat:@"%.1f dB", 0.0];
    self.phaseLabel.text = [NSString stringWithFormat:@"%.1f˚", 0.0];
}

#pragma mark - Reader Event Handler Methods
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
//    [appDelegate.mReader setSacnModel:RFIDScanModel];
    if (status) {
        [self readAction];
    }
    return NO;
}
- (BOOL)onAsReaderLeftModeKeyEvent:(BOOL)status{
    if(appDelegate.mReader.isRFIDModule&&appDelegate.mReader.isBarcodeModule){
        return YES;
    }
    return NO;
}
- (BOOL)onAsReaderRightModeKeyEvent:(BOOL)status{
    if(appDelegate.mReader.isRFIDModule&&appDelegate.mReader.isBarcodeModule){
        return YES;
    }
    return NO;
}
- (void)updateDeviceState:(ResultCode)error {
    if (error != ResultNoError) {
        [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];

         currentAlertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Failed to get response. Try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)readTag:(NSString *)tag rssi:(float)rssi phase:(float)phase {
    NSLog(@"RMV - Read Tag : %@", tag);
}

- (void)changedActionState:(CommandType)action resultCode:(NSInteger)resultCode {
    NSLog(@"RMV - Changed Action State to : %x", action);
    
    if (action == CommandStop) {
        [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
        
        if (isActionResult == NO)
            self.messageLabel.text = MSG_TAG_WAIT;
    }
}

- (void)accessResult:(ResultCode)error actionState:(CommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase frequency:(float)frequency{
    
    isActionResult = YES;
    
    if (error != ResultNoError) {
        [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
        
        self.messageLabel.text = [AsResultCode msg:error];
        
        currentAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[AsResultCode msg:error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        return;
    }
    
    self.messageLabel.text = @"Success";
    self.selectionTagLabel.text = epc;
    
    self.address1Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)self.offsetValue];
    self.address2Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 1)];
    self.address3Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 2)];
    self.address4Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 3)];
    self.address5Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 4)];
    self.address6Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 5)];
    self.address7Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 6)];
    self.address8Label.text = [[NSString alloc] initWithFormat:@"%d WORD", (int)(self.offsetValue + 7)];
    
    NSArray *bitLabel = [data componentsSeparatedByString:@","];
    int bitLabelCount = (int)[bitLabel count];
    
    if (bitLabelCount >= 1) {
        self.value1Label.text = [bitLabel objectAtIndex:0];
    } else {
        self.value1Label.text = @"0000";
    }
    if (bitLabelCount >= 2) {
        self.value2Label.text = [bitLabel objectAtIndex:1];
    } else {
        self.value2Label.text = @"0000";
    }
    if (bitLabelCount >= 3) {
        self.value3Label.text = [bitLabel objectAtIndex:2];
    } else {
        self.value3Label.text = @"0000";
    }
    if (bitLabelCount >= 4) {
        self.value4Label.text = [bitLabel objectAtIndex:3];
    } else {
        self.value4Label.text = @"0000";
    }
    if (bitLabelCount >= 5) {
        self.value5Label.text = [bitLabel objectAtIndex:4];
    } else {
        self.value5Label.text = @"0000";
    }
    if (bitLabelCount >= 6) {
        self.value6Label.text = [bitLabel objectAtIndex:5];
    } else {
        self.value6Label.text = @"0000";
    }
    if (bitLabelCount >= 7) {
        self.value7Label.text = [bitLabel objectAtIndex:6];
    } else {
        self.value7Label.text = @"0000";
    }
    if (bitLabelCount >= 8) {
        self.value8Label.text = [bitLabel objectAtIndex:7];
    } else {
        self.value8Label.text = @"0000";
    }
    
    if (![self.reportRssiSwitch isOn]) {
        [self setReportRssiModeDefault];
    } else {
        self.rssiLabel.text = [NSString stringWithFormat:@"%.1f dB", rssi];
        self.phaseLabel.text = [NSString stringWithFormat:@"%.1f˚", phase];
    }
    
    [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - NSNotification
- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = nil;
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}
- (void)AsReaderGUNConnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = [[AsReader alloc] initWithAsReaderGUN:appDelegate.mAsReaderGUN delegate:self];
        [self viewDidAppear:YES];
    });
}
@end
