//
//  RFIDOptionViewController.m
//  AT288N_DEMO
//
//  Created by 류은주 on 2017. 7. 28..
//  Copyright © 2017년 ATID. All rights reserved.
//
#define ALERT_VIEW_MASK     0


#define PICKER_VIEW_POWER_GAIN          0
#define PICKER_VIEW_MASK_BANK           1
#define PICKER_VIEW_MASK_OFFSET         2
#define PICKER_VIEW_MASK_ACTION         3
#define PICKER_VIEW_INVENTORY_TYPE      4
#define PICKER_VIEW_INVENTORY_FORMAT    5
#define PICKER_VIEW_GEN_TYPE            6


#import "RFIDOptionViewController.h"
#import "OptionTableViewCell.h"
#import "SWRevealViewController.h"
#import <objc/runtime.h>

@interface ChannelItem (Frequency) {
    
}
@property (strong, nonatomic) NSString *frequency;
@end

@implementation ChannelItem (Frequency)

static char UIB_FREQUENCY_KEY;

@dynamic frequency;

- (void)setFrequency:(NSString *)frequency {
    objc_setAssociatedObject(self, &UIB_FREQUENCY_KEY, frequency, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (NSString *)frequency {
    return (NSString *)objc_getAssociatedObject(self, &UIB_FREQUENCY_KEY);
}
@end

@interface RFIDOptionViewController ()
{
    NSArray *rfidmenuItems;

    NSArray *countryarray;

     ResultType res ;
    NSMutableArray *tmpArray;
    
    NSString *country;
    NSString *powergaintext;
    
    int selectedcell;
    
    BOOL isShowingAlert;
    
    int pickerindex;
    
    NSString *maskstring;
    
    int postpowergain;
}

@property (weak, nonatomic) IBOutlet UILabel *rfidoptionLabel;
@property (weak, nonatomic) IBOutlet UITableView *rfidOptionTableView;
@property (weak, nonatomic) IBOutlet UITableView *lbtTableView;
@property (weak, nonatomic) IBOutlet UIPickerView *powergainpicker;
@property (weak, nonatomic) IBOutlet UIView *pickertopview;
@property (weak, nonatomic) IBOutlet UIView *lbttableTopView;
@property (strong, nonatomic) NSArray *lbtItemData;
@property (strong, nonatomic) NSArray *arrayOfEncode;
@property (strong, nonatomic) NSArray *powerGainPickerData;
@property (strong, nonatomic) NSArray *bankPickerData;
@property (strong, nonatomic) NSArray *offsetPickerData;
@property (strong, nonatomic) NSArray *actionPickerData;
@property (strong, nonatomic) NSArray *inventorytypearray;
@property (strong, nonatomic) NSArray *inventoryFormatArray;
@property (weak, nonatomic) IBOutlet UIView *bankPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *offsetPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *actionPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *masksetView;
@property (weak, nonatomic) IBOutlet UIView *masksetTopView;
@property (weak, nonatomic) IBOutlet UITextField *bankTextField;
@property (weak, nonatomic) IBOutlet UITextField *offsetTextField;
@property (weak, nonatomic) IBOutlet UITextField *actionTextField;
@property (weak, nonatomic) IBOutlet UITextField *maskStrTextField;
@property (readwrite, nonatomic) int maskBank;
@property (readwrite, nonatomic) int maskOffset;
@property (readwrite, nonatomic) int maskAction;
@property (weak, nonatomic) IBOutlet UIView *shadowview;

@end

@implementation RFIDOptionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    if (appDelegate.mReader == nil) {
        return;
    }
  //  dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Do something...
        
        isShowingAlert = NO;
        
        postpowergain = 0;
        
        if(appDelegate.mReader.firmwareType == FIRMWARE_MI){
            rfidmenuItems = @[@"Global Band",@"Inventory Type",@"Scan Time",@"Power Gain",@"Inventory Time",@"Idle Time",@"Save Tag",@"Inventory Format",@"Selection Mask"];
        }else if((appDelegate.mReader.firmwareType == FIRMWARE_MA) && (appDelegate.mReader.typeBC == FIRMWARE_MA)){
            rfidmenuItems = @[@"Global Band",@"Gen2 6C/6B Tag Type",@"Inventory Type",@"Scan Time",@"Power Gain",@"Inventory Time",@"Idle Time",@"Save Tag",@"Inventory Format"];
        }else {
            rfidmenuItems = @[@"Global Band",@"Gen2 6C/6B Tag Type",@"Inventory Type",@"Scan Time",@"Power Gain",@"Inventory Time",@"Idle Time",@"Save Tag",@"Inventory Format",@"Selection Mask"];
        }
        NSLog(@"viewWillAppear rfidmenuItems setting");
        if(appDelegate.mReader.firmwareType == FIRMWARE_MI){
            countryarray = @[@"Korea", @"Europe", @"USA",@"China",@"Taiwan", @"Brazil", @"Malaysia",@"ASIA",@"Japan",@"Japan",@"India",@"Indonesia",@"Japan",@"Israel",@"Australia",@"Newzealand",@"Philippines",@"Singapore",@"Thailand",@"Uruguay",@"Vietnam",@"South Africa",@"Chile 1W",@"Chile 0.5W",@"Canda",@"Mexco",@"Argentina",@"Morocco"];
        } else {
            countryarray = @[@"Korea",@"Japan", @"Europe", @"USA",@"China",@"Taiwan", @"Brazil", @"Malaysia",@"ASIA",@"India",@"Indonesia",@"Israel",@"Australia",@"Newzealand",@"Philippines",@"Singapore",@"Thailand",@"Uruguay",@"Vietnam",@"South Africa",@"Morocco"];
        }
        
        _powerGainPickerData = @[@"30 dB",@"29 dB",@"28 dB",@"27 dB",@"26 dB",@"25 dB",@"24 dB",@"23 dB",@"22 dB",@"21 dB",@"20 dB",@"19 dB",@"18 dB",@"17 dB",@"16 dB",@"15 dB",@"14 dB",@"13 dB",@"12 dB",@"11 dB"];
   // });
    
}
- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
   // dispatch_async(dispatch_get_main_queue(), ^{
//        [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
        HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
        HUD.labelText = @"Loading...";
        [self.navigationController.view addSubview:HUD];
        [HUD show:YES];
 //   });
    
    
    
}
- (void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(BluetoothDisconnected:) name:@"BluetoothDisconnected" object:nil];
    dispatch_async(dispatch_get_main_queue(), ^{

           // [self.rfidoptionLabel setHidden:NO];
           // [self.rfidOptionTableView setHidden: NO];

        [AppDelegate dismissGlobalHUD];
        [HUD hide:YES];
        [HUD removeFromSuperview];
    });
    
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    dispatch_async(dispatch_get_main_queue(), ^{
        [AppDelegate dismissGlobalHUD];
        [HUD hide:YES];
        [HUD removeFromSuperview];
    });
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BluetoothDisconnected" object:nil];
    self.inventoryview = 0;
    [appDelegate.mReader saveData];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}
#pragma mark - Storyboard Segue
-(IBAction)prepareForUnwind:(UIStoryboardSegue *)segue sender:(id)sender {
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if(tableView == _rfidOptionTableView){
        NSLog(@" _rfidOptionTableView count %lu",(unsigned long)rfidmenuItems.count);
        return rfidmenuItems.count;
    } else {
        NSLog(@" _lbtItemData count %lu",(unsigned long)_lbtItemData.count);
        return _lbtItemData.count;
    }
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (tableView == _rfidOptionTableView){
        NSString *CellIdentifier = [rfidmenuItems objectAtIndex:indexPath.row];
                    NSString *country = [countryarray objectAtIndex:appDelegate.mReader.globalBand];
        
        
        OptionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RfidOptionCell" forIndexPath:indexPath];
        
        cell.memuname.text = CellIdentifier;
        dispatch_async(dispatch_get_main_queue(), ^{
            if(appDelegate.mReader.firmwareType == FIRMWARE_MI){
                if(indexPath.row == 0){
                    cell.menuvalue.text = country;
                }else if(indexPath.row == 1){
                    cell.menuvalue.text = [self.inventorytypearray objectAtIndex:[appDelegate.mReader singleMulti]];
                }else if(indexPath.row == 2){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d s",[appDelegate.mReader scanTime]];
                }else if(indexPath.row == 3){
                    cell.menuvalue.text = [_powerGainPickerData objectAtIndex:[appDelegate.mReader powerGain]];
                }else if(indexPath.row == 4){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d ms",[appDelegate.mReader antennaSwitchingTime]];
                }else if(indexPath.row == 5){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d ms",[appDelegate.mReader idleTime]];
                }else if(indexPath.row == 6){
                    if([appDelegate.mReader saveMode]){
                        cell.menuvalue.text = @"ON";
                    } else {
                        cell.menuvalue.text = @"OFF";
                    }
                }else if(indexPath.row == 7){
                    cell.menuvalue.text = [self.inventoryFormatArray objectAtIndex:[appDelegate.mReader inventoryFormat]];
                }else {
                    cell.menuvalue.text = nil;
                }
            }else {
                if(indexPath.row == 0){
                    cell.menuvalue.text = country;
                }else if(indexPath.row == 1){
                    cell.menuvalue.text = [self.genTypeArray objectAtIndex:[appDelegate.mReader typeBC]];
                }else if(indexPath.row == 2){
                    cell.menuvalue.text = [self.inventorytypearray objectAtIndex:[appDelegate.mReader singleMulti]];
                }else if(indexPath.row == 3){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d s",[appDelegate.mReader scanTime]];
                }else if(indexPath.row == 4){
                    cell.menuvalue.text = [_powerGainPickerData objectAtIndex:[appDelegate.mReader powerGain]];
                }else if(indexPath.row == 5){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d ms",[appDelegate.mReader antennaSwitchingTime]];
                }else if(indexPath.row == 6){
                    cell.menuvalue.text = [NSString stringWithFormat:@"%d ms",[appDelegate.mReader idleTime]];
                }else if(indexPath.row == 7){
                    if([appDelegate.mReader saveMode]){
                        cell.menuvalue.text = @"ON";
                    } else {
                        cell.menuvalue.text = @"OFF";
                    }
                }else if(indexPath.row == 8){
                    cell.menuvalue.text = [self.inventoryFormatArray objectAtIndex:[appDelegate.mReader inventoryFormat]];
                }else {
                    cell.menuvalue.text = nil;
                }
            }
        });

        return cell;
        
    }else {
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LbtCell" forIndexPath:indexPath];
        
        ChannelItem *lbtItem = [self.lbtItemData objectAtIndex:indexPath.row];
        
        if (lbtItem.mIsUsed) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        }
        
        cell.textLabel.text = lbtItem.frequency;
        
        return cell;
    }
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    if (tableView == _rfidOptionTableView){
        if(appDelegate.mReader.firmwareType == FIRMWARE_MI){
            if(indexPath.row == 0){
                
            }else if (indexPath.row == 1){
                if(self.inventoryview){
                    [self inventorytypesetting];
                }
            }else if (indexPath.row == 2){
                [self scanTime];
            }else if (indexPath.row == 3){
                [self powergainsetting];
            }else if (indexPath.row == 4){
                [self inventorytime];
            }else if (indexPath.row == 5){
                [self idletime];
            }else if(indexPath.row == 6){
                if([appDelegate.mReader saveMode]){
                    appDelegate.mReader.saveMode = 0;
                } else {
                    appDelegate.mReader.saveMode = 1;
                }
            }else if(indexPath.row == 7){
                [self inventoryformatsetting];
            }else if (indexPath.row == 8){
                [self initmaskset];
                self.masksetView.hidden = NO;
                self.masksetTopView.hidden = NO;
                self.shadowview.hidden = NO;
            }else{
                
            }
        } else {
            if(indexPath.row == 0){
                
            }else if (indexPath.row == 1){
                if(self.inventoryview){
                [self gentypesetting];
                }
            }else if (indexPath.row == 2){
                if(self.inventoryview){
                    [self inventorytypesetting];
                }
            }else if (indexPath.row == 3){
                [self scanTime];
            }else if (indexPath.row == 4){
                [self powergainsetting];
            }else if (indexPath.row == 5){
                [self inventorytime];
            }else if (indexPath.row == 6){
                [self idletime];
            }else if(indexPath.row == 7){
                if([appDelegate.mReader saveMode]){
                    appDelegate.mReader.saveMode = 0;
                } else {
                    appDelegate.mReader.saveMode = 1;
                }
            }else if(indexPath.row == 8){
                [self inventoryformatsetting];
            }else if (indexPath.row == 9){
                [self initmaskset];
                self.masksetView.hidden = NO;
                self.masksetTopView.hidden = NO;
                self.shadowview.hidden = NO;
            }else{
                
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [_rfidOptionTableView reloadData];
        });
        
    }
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_POWER_GAIN) {
        return [self.powerGainPickerData count];
    }else if (pickerView.tag == PICKER_VIEW_MASK_ACTION) {
        return self.actionPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_MASK_BANK) {
        return self.bankPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_MASK_OFFSET) {
        return self.offsetPickerData.count;
    }else if (pickerView.tag == PICKER_VIEW_INVENTORY_TYPE) {
        return self.inventorytypearray.count;
    }else if (pickerView.tag == PICKER_VIEW_INVENTORY_FORMAT) {
        return self.inventoryFormatArray.count;
    }else if (pickerView.tag == PICKER_VIEW_GEN_TYPE) {
        return self.genTypeArray.count;
    }
    return 0;
    
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_POWER_GAIN) {
        return [self.powerGainPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_MASK_ACTION) {
        return [self.actionPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_MASK_BANK) {
        return [self.bankPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_MASK_OFFSET) {
        return [self.offsetPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_INVENTORY_TYPE) {
        return [self.inventorytypearray objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_INVENTORY_FORMAT) {
        return [self.inventoryFormatArray objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_GEN_TYPE) {
        return [self.genTypeArray objectAtIndex:row];
    }
    return @"None";
    
}
#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == ALERT_VIEW_MASK) {
        if (buttonIndex == 1) {
            [self setMask:[alertView textFieldAtIndex:0].text];
        } 
    }
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    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;
}

- (IBAction)topViewBackBtnTapped:(id)sender {
    [self hideviewtables];
}
- (IBAction)topviewDoneBtnTapped:(id)sender {
    res = ResultNoError;
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Saving...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
//            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
        });
    });
    
    [self hideviewtables];
    
    
}
- (IBAction)lbttopviewOKTapped:(id)sender {
    [self hideviewtables];
}
- (void) hideviewtables {
    
    self.lbtTableView.hidden = YES;
    self.shadowview.hidden = YES;
    self.lbttableTopView.hidden = YES;
    self.powergainpicker.hidden = YES;
    self.pickertopview.hidden = YES;
    self.masksetTopView.hidden = YES;
    self.masksetView.hidden = YES;
}
- (void) powergainsetting {
    self.powergainpicker.tag = PICKER_VIEW_POWER_GAIN;
    pickerindex = PICKER_VIEW_POWER_GAIN;
    [self.powergainpicker reloadAllComponents];
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        if (![powergaintext isEqualToString:@""]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.powergainpicker selectRow:appDelegate.mReader.powerGain inComponent:0 animated:NO];
            });
        } else {
            [self.powergainpicker selectRow:0 inComponent:0 animated:NO];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            self.powergainpicker.hidden = false;
            self.pickertopview.hidden = false;
            self.shadowview.hidden = false;
        });
    });
}
- (void) gentypesetting {
    
    self.powergainpicker.tag = PICKER_VIEW_GEN_TYPE;
    pickerindex = PICKER_VIEW_GEN_TYPE;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:appDelegate.mReader.typeBC inComponent:0 animated:NO];
    
    self.powergainpicker.hidden = false;
    self.pickertopview.hidden = false;
    self.shadowview.hidden = false;
    
}
- (void) inventorytypesetting {
    
    self.powergainpicker.tag = PICKER_VIEW_INVENTORY_TYPE;
    pickerindex = PICKER_VIEW_INVENTORY_TYPE;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:appDelegate.mReader.singleMulti inComponent:0 animated:NO];
    
    self.powergainpicker.hidden = false;
    self.pickertopview.hidden = false;
    self.shadowview.hidden = false;
    
}
- (void) inventoryformatsetting {
    self.powergainpicker.tag = PICKER_VIEW_INVENTORY_FORMAT;
    pickerindex = PICKER_VIEW_INVENTORY_FORMAT;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:appDelegate.mReader.inventoryFormat inComponent:0 animated:NO];
    
    self.powergainpicker.hidden = false;
    self.pickertopview.hidden = false;
    self.shadowview.hidden = false;
    
}
- (IBAction)defaultBtnTapped:(id)sender {
    if([appDelegate.mReader setAllDefault] == ResultNoError){
        [self.rfidOptionTableView reloadData];
        appDelegate.inventorymode = appDelegate.mReader.singleMulti;
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Failed to get response. Try again." preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *ok = [UIAlertAction
                             actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action){
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                             }];
        [alert addAction:ok];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
   
}
- (IBAction)powergaintopviewcancel:(id)sender {
    [self hideviewtables];
}
- (IBAction)powergaintopviewconfirm:(id)sender {
    NSInteger idx = [self.powergainpicker selectedRowInComponent:0];
     [self.rfidOptionTableView reloadData];
    if(pickerindex ==  PICKER_VIEW_POWER_GAIN){
        appDelegate.mReader.powerGain = (int)idx;
    } else if (pickerindex ==  PICKER_VIEW_INVENTORY_TYPE){
        appDelegate.mReader.singleMulti = (int)idx;
        if(self.inventoryview == 1){
            appDelegate.inventorymode = appDelegate.mReader.singleMulti;
        }
    } else if (pickerindex == PICKER_VIEW_INVENTORY_FORMAT){
        appDelegate.mReader.inventoryFormat = (int)idx;
//        [_rfidOptionTableView reloadData];
    } else if (pickerindex == PICKER_VIEW_GEN_TYPE){
        appDelegate.mReader.typeBC = (int)idx;
     //   dispatch_async(dispatch_get_main_queue(), ^{
            if(appDelegate.mReader.typeBC == FIRMWARE_MA){
                rfidmenuItems = @[@"Global Band",@"Gen2 6C/6B Tag Type",@"Inventory Type",@"Scan Time",@"Power Gain",@"Inventory Time",@"Idle Time",@"Save Tag",@"Inventory Format"];
            }else {
                rfidmenuItems = @[@"Global Band",@"Gen2 6C/6B Tag Type",@"Inventory Type",@"Scan Time",@"Power Gain",@"Inventory Time",@"Idle Time",@"Save Tag",@"Inventory Format",@"Selection Mask"];
            }
            [_rfidOptionTableView reloadData];
  //      });
        
    }
    [self hideviewtables];
}
- (IBAction)masksetViewCancel:(id)sender {
    [self hideviewtables];
}
- (IBAction)masksetOK:(id)sender {
    appDelegate.mReader.selectionBank = self.maskBank;
    appDelegate.mReader.selectBitPtr = self.maskOffset;
    appDelegate.mReader.selectAction = self.maskAction;
    appDelegate.maskstrvalue = maskstring;
    [self hideviewtables];
}
- (void)initmaskset {
        [self setBank:appDelegate.mReader.selectionBank];
        // Update Session Type
        [self setoffset:(appDelegate.mReader.selectBitPtr/16)];
        
        // Update Flip Mode
        [self setaction:appDelegate.mReader.selectAction];
        
        [self setMask:appDelegate.maskstrvalue];
}

- (NSArray *)bankPickerData {
    return DATA_BANK;
}
- (NSArray *)offsetPickerData {
    if (_offsetPickerData == nil) {
        NSMutableArray *offsetArray = [[NSMutableArray alloc] init];
        for (NSString *offset in DATA_WORD) {
            [offsetArray addObject:[NSString stringWithFormat:@"%@ WORD", offset]];
        }
        _offsetPickerData = offsetArray;
    }
    return _offsetPickerData;
}
- (NSArray *)actionPickerData {
    return DATA_ACTION;
    
}
- (NSArray *)inventorytypearray {
    if(appDelegate.mReader.firmwareType == FIRMWARE_MI){
        return DATA_INVENTORY_TYPE_MI;
    }else {
        return DATA_INVENTORY_TYPE_MA;
    }
}

- (NSArray *)inventoryFormatArray{
    if((appDelegate.mReader.firmwareType == FIRMWARE_MA)&&(appDelegate.mReader.typeBC == FIRMWARE_MA)){
        return DATA_INVENTORY_FORMAT_MA;
    } else {
        return DATA_INVENTORY_FORMAT_MI;
    }
}

- (NSArray *)genTypeArray{
    return DATA_GEN_TYPE;
}
- (void)setBank:(int)bank {
    self.bankTextField.text = [self.bankPickerData objectAtIndex:bank];
    _maskBank = bank;
}

- (void)setoffset:(int)offset {
    self.offsetTextField.text = [self.offsetPickerData objectAtIndex:offset];
    _maskOffset = (offset*16);
}

- (void)setaction:(int)action {
    self.actionTextField.text = [self.actionPickerData objectAtIndex:action];
    _maskAction = action;
}
- (void)setMask:(NSString *)mask {
    self.maskStrTextField.text = mask;
    maskstring = mask;
    //    self.selectMaskParam.mask = mask;
}
- (IBAction)maskActionBtnTapped:(id)sender {
    [self.masksetView setHidden: YES];
    [self.masksetTopView setHidden: YES];
    self.powergainpicker.tag = PICKER_VIEW_MASK_ACTION;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:self.maskAction inComponent:0 animated:NO];
    
    self.powergainpicker.hidden = NO;
    self.actionPickerTopView.hidden = NO;
}
- (IBAction)maskBankBtnTapped:(id)sender {
    [self.masksetView setHidden: YES];
    [self.masksetTopView setHidden: YES];
    self.powergainpicker.tag = PICKER_VIEW_MASK_BANK;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:self.maskBank inComponent:0 animated:NO];
    
    self.powergainpicker.hidden = NO;
    self.bankPickerTopView.hidden = NO;
}
- (IBAction)maskOffsetBtnTapped:(id)sender {
    [self.masksetView setHidden: YES];
    [self.masksetTopView setHidden: YES];
    self.powergainpicker.tag = PICKER_VIEW_MASK_OFFSET;
    [self.powergainpicker reloadAllComponents];
    
    [self.powergainpicker selectRow:(self.maskOffset/16) inComponent:0 animated:NO];
    self.
    self.powergainpicker.hidden = NO;
    self.offsetPickerTopView.hidden = NO;
}
- (IBAction)maskstrBtnTapped:(id)sender {
    UIAlertView *alert;
    
    alert = [[UIAlertView alloc] initWithTitle:@"Mask:" message:@"Please enter mask value." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
    [alert textFieldAtIndex:0].delegate = self;
    [alert textFieldAtIndex:0].text = self.maskStrTextField.text;
    alert.tag = ALERT_VIEW_MASK;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];

    
    
}
- (IBAction)maskBankPickerOkBtnTapped:(id)sender {
    [self setBank:(int)[self.powergainpicker selectedRowInComponent:0]];
    
    [self hidePickerView];
}
- (IBAction)maskOffsetPickerOkBtnTapped:(id)sender {
    [self setoffset:(int)[self.powergainpicker selectedRowInComponent:0]];
    
    [self hidePickerView];
}
- (IBAction)maskActionPickerOkBtnTapped:(id)sender {
    [self setaction:(int)[self.powergainpicker selectedRowInComponent:0]];
    
    [self hidePickerView];
}
- (IBAction)masksetCancelTapped:(id)sender {
    [self hidePickerView];
}
- (IBAction)masksetResetBtn:(id)sender {
    [self setBank:1];
    [self setoffset:2];
    [self setaction:0];
    [self setMask:@""];
}

- (void)hidePickerView {
    [self.masksetView setHidden: NO];
    [self.masksetTopView setHidden: NO];
    self.powergainpicker.hidden = YES;
    self.bankPickerTopView.hidden = YES;
    self.offsetPickerTopView.hidden = YES;
    self.actionPickerTopView.hidden = YES;
}
- (void) inventorytime {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Inventory Time:" message:@"Please enter Inventory time.\n(ex: 30 ms)" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             UITextField* textField = alert.textFields.firstObject;
                             if([textField.text intValue]<1){
                                 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Please enter a number greater than 0." preferredStyle:UIAlertControllerStyleAlert];

                                 UIAlertAction *ok = [UIAlertAction
                                                      actionWithTitle:@"OK"
                                                      style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action){
                                                          [alert dismissViewControllerAnimated:YES completion:nil];
                                                      }];
                                 [alert addAction:ok];

                                 [self presentViewController:alert animated:YES completion:nil];
                             }else {
                             appDelegate.mReader.antennaSwitchingTime = [textField.text intValue];
                             
                             [self.rfidOptionTableView reloadData];
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                             }
                         
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
}

- (void) idletime {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Idle Time:" message:@"Please enter idle time.\n(ex: 30 ms)" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             UITextField* textField = alert.textFields.firstObject;
                             if([textField.text intValue]<1){
                                 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Please enter a number greater than 0." preferredStyle:UIAlertControllerStyleAlert];
                                 
                                 UIAlertAction *ok = [UIAlertAction
                                                      actionWithTitle:@"OK"
                                                      style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action){
                                                          [alert dismissViewControllerAnimated:YES completion:nil];
                                                      }];
                                 [alert addAction:ok];
                                 
                                 [self presentViewController:alert animated:YES completion:nil];
                             }else {
                             appDelegate.mReader.idleTime = [textField.text intValue];
                             
                             [self.rfidOptionTableView reloadData];
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                             }
                             
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}
- (void) autoofftime {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Auto Off Time:" message:@"Please enter auto off time.\n(ex: 3 min)" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             UITextField* textField = alert.textFields.firstObject;
                             
                             appDelegate.mReader.autoOffTime = [textField.text intValue];
                             
                             [self.rfidOptionTableView reloadData];
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                             
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}
- (void) operationtime {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Operation Time:" message:@"Please enter operataion time.\n(ex: 30 ms)" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             UITextField* textField = alert.textFields.firstObject;
                             
                             appDelegate.mReader.operationTime = [textField.text intValue];
                             
                             [self.rfidOptionTableView reloadData];
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                             
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - NSNotification
- (void)BluetoothDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"BluetoohDisconnected");
        //[self.navigationController popToRootViewControllerAnimated:YES];
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
}
/*+ej_ryu+*/
- (void) powergainchange:(int)gain {
    powergaintext = [NSString stringWithFormat:@"%i.0 dB",gain/10];
    if(postpowergain != gain){
        postpowergain = gain;
        dispatch_async(dispatch_get_main_queue(), ^{
            [_rfidOptionTableView reloadData];
        });
    }

}
- (void) scanTime {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Scan Time:" message:@"Please enter Memory Access time.\n(ex: 5 s)" preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action)
                         {
                             UITextField* textField = alert.textFields.firstObject;
                             if([textField.text intValue]<5){
                                 UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Please enter a number greater than 5." preferredStyle:UIAlertControllerStyleAlert];
                                 
                                 UIAlertAction *ok = [UIAlertAction
                                                      actionWithTitle:@"OK"
                                                      style:UIAlertActionStyleDefault
                                                      handler:^(UIAlertAction * action){
                                                          [alert dismissViewControllerAnimated:YES completion:nil];
                                                      }];
                                 [alert addAction:ok];
                                 
                                 [self presentViewController:alert animated:YES completion:nil];
                             }else {
                                 appDelegate.mReader.scanTime = [textField.text intValue];
                                 
                                 [self.rfidOptionTableView reloadData];
                                 
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                             }
                             
                         }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                                 
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self presentViewController:alert animated:YES completion:nil];
    });
}
/*-ej_tyu-*/

@end
