#define PICKER_VIEW_BUZZER          0
#define PICKER_VIEW_KEY_ACTION      1
#define PICKER_VIEW_MASK_TYPE       2
#define PICKER_VIEW_Vibrator        3
#define PICKER_VIEW_QValue          4
#define PICKER_VIEW_Algorithm       5
#define PICKER_VIEW_MaxQValue       6
#define PICKER_VIEW_MinQValue       7
#define PICKER_VIEW_Link_Profile               8
#define PICKER_VIEW_Default_Link_Profile       9
/*Robin*/
#define PICKER_VIEW_HST_RFTC_FWDPWRTHRSH       10




#define ALERT_VIEW_INTERVAL_TIME    0
#define ALERT_VIEW_IDLE_TIME        1
#define ALERT_VIEW_AUTO_OFF_TIME    2
#define ALERT_VIEW_BATTERY_INTERVAL 3
#define ALERT_VIEW_SLEEP_TIME       4
#define ALERT_VIEW_THRESHOLD        5

#import "OptionsViewController.h"
#import "UserData.h"
#import "SystemSetting.h" 

@interface OptionsViewController () {
    SystemSetting * systemSetting;
}
@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *setLBTButton;

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *buzzerTextField;
@property (weak, nonatomic) IBOutlet UITextField *vibratorTextField;
@property (weak, nonatomic) IBOutlet UITextField *inventoryTimeTextField;
@property (weak, nonatomic) IBOutlet UITextField *idleTimeTextField;
@property (weak, nonatomic) IBOutlet UITextField *autoOffTimeTextField;
@property (weak, nonatomic) IBOutlet UITextField *keyActionTextField;
@property (weak, nonatomic) IBOutlet UITextField *batteryIntervalTextField;
@property (weak, nonatomic) IBOutlet UITextField *maskTypeTextField;
@property (weak, nonatomic) IBOutlet UIView *buzzerPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *vibratorPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *keyActionPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *maskTypePickerTopView;
@property (weak, nonatomic) IBOutlet UIView *lbtChannelTableTopView;
@property (weak, nonatomic) IBOutlet UIView *shadowView;
@property (strong, nonatomic) NSArray *buzzerPickerData;
@property (strong, nonatomic) NSArray *vibratorPickerData;
@property (strong, nonatomic) NSArray *keyActionPickerData;
@property (strong, nonatomic) NSArray *maskTypePickerData;
@property (strong, nonatomic) NSArray *lbtItemData;
@property (readwrite, nonatomic) BuzzerState buzzerValue;
@property (readwrite, nonatomic) VibratorState vibratorValue;
@property (readwrite, nonatomic) NSInteger inventoryTimeValue;
@property (readwrite, nonatomic) NSInteger idleTimeValue;
@property (readwrite, nonatomic) NSInteger autoOffTimeValue;
@property (readwrite, nonatomic) NSInteger keyActionValue;
@property (strong, nonatomic) NSString *batteryIntervalValue;
@property (readwrite, nonatomic) MaskType maskTypeValue;

@property (weak, nonatomic) IBOutlet UITextField *algorithmTextField;
@property (readwrite, nonatomic) AlgorithmType algorithmValue;
@property (strong, nonatomic) NSArray *algorithmPickerData;
@property (weak, nonatomic) IBOutlet UIView *algorithmPickerTopView;

@property (weak, nonatomic) IBOutlet UITextField *qValueTextField;
@property (readwrite, nonatomic) NSInteger qValue;
@property (strong, nonatomic) NSArray *qValuePickerData;
@property (weak, nonatomic) IBOutlet UIView *qValuePickerTopView;

@property (weak, nonatomic) IBOutlet UITextField *minQValueTextField;
@property (readwrite, nonatomic) NSInteger minQValue;

@property (weak, nonatomic) IBOutlet UITextField *maxQValueTextField;
@property (readwrite, nonatomic) NSInteger maxQValue;


@property (strong, nonatomic) NSArray *linkProfilePickerData;
@property (readwrite, nonatomic) NSInteger linkProfileValue;
@property (weak, nonatomic) IBOutlet UITextField *linkProfileTextField;


@property (readwrite, nonatomic) NSInteger defaultLinkProfileValue;
@property (weak, nonatomic) IBOutlet UITextField *defaultLinkProfileTextField;
@property (weak, nonatomic) IBOutlet UITextField *sleepTimeTextField;
@property (readwrite, nonatomic) NSInteger sleepTimeValue;

@property (weak, nonatomic) IBOutlet UIView *LinkProfileTableTopView;

@property (weak, nonatomic) IBOutlet UITextField *thresHoldTextField;

@property (readwrite, nonatomic) NSInteger thresHoldValue;

@end

@implementation OptionsViewController{
    BOOL isJapan;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    isJapan = NO;
    systemSetting = [SystemSetting sharedSystemSetting];
    self.scrollView.contentSize = CGSizeMake(0, 1000);
    self.scrollView.showsVerticalScrollIndicator = NO;
}

- (void)viewWillAppear:(BOOL)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 showGlobalProgressHUDWithTitle:@"Loading..."];
    
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    if (appDelegate.mReader == nil) {
        [AppDelegate dismissGlobalHUD];
        return;
    }
    self.vibratorValue = appDelegate.mReader.vibrator;
    self.buzzerValue = appDelegate.mReader.buzzer;
    self.inventoryTimeValue = appDelegate.mReader.inventoryTime;
    self.idleTimeValue = appDelegate.mReader.idleTime;
    self.autoOffTimeValue = appDelegate.mReader.autoOffTime;
    self.qValue = appDelegate.mReader.qValue;
    self.maxQValue = appDelegate.mReader.maxQ;
    self.minQValue = appDelegate.mReader.minQ;
    self.algorithmValue = appDelegate.mReader.algorithm;
    self.linkProfileValue = appDelegate.mReader.linkProfileValue;
    self.defaultLinkProfileValue = appDelegate.mReader.defaultLinkProfileValue;
    self.maskTypeValue = appDelegate.mReader.maskTypeValue;
    self.sleepTimeValue = appDelegate.mReader.sleepTime;
    self.thresHoldValue = appDelegate.mReader.thresHoldValue;
    isJapan = [[appDelegate.mReader regionName] hasPrefix:@"Japan"];
    if (isJapan) {
        _setLBTButton.hidden = NO;
        [self initLbtItemData];
    }else{
        _setLBTButton.hidden = YES;
    }
    [self initViewData];
    [self.tableView reloadData];
    [self.navigationController.view addSubview:self.shadowView];
    [AppDelegate dismissGlobalHUD];
}

- (void)viewWillDisappear:(BOOL)animated {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNConnected" object:nil];
}


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


- (IBAction)adminBtnAction:(id)sender {
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Enter your Password" message:@"" preferredStyle:UIAlertControllerStyleAlert];
    
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"Current Password";
        textField.secureTextEntry = YES;
    }];
    
    
    
    
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Current Password %@", [[alertController textFields][0] text]);
        
        if(![alertController.textFields.firstObject.text isEqual:@"111111"]){
            
            UIAlertController *alert=   [UIAlertController
                                         alertControllerWithTitle:@"Please check your password and try again"
                                         message:@""
                                         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{
            
            UIViewController *controller = [self.storyboard instantiateViewControllerWithIdentifier:@"RegionSettingViewController"];
            [self.navigationController pushViewController:controller animated:YES];
            
        }
    }];
    
    [alertController addAction:confirmAction];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Canelled");
    }];
    
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}





#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.lbtItemData.count;
}

#pragma mark - UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"LbtCell" forIndexPath:indexPath];
    
    LbtItem *lbtItem = [self.lbtItemData objectAtIndex:indexPath.row];
    
    if (lbtItem.mIsUsed) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else{
        cell.accessoryType = UITableViewCellAccessoryNone;
        
    }
    
    cell.textLabel.text = lbtItem.frequency;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    LbtItem *lbtItem = [self.lbtItemData objectAtIndex:indexPath.row];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        lbtItem.mIsUsed = NO;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        lbtItem.mIsUsed = YES;
    }
    
}

-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    LbtItem *lbtItem = [self.lbtItemData objectAtIndex:indexPath.row];
    if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;
        lbtItem.mIsUsed = NO;
    } else {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        lbtItem.mIsUsed = YES;
    }
}


#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_BUZZER) {
        return self.buzzerPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_KEY_ACTION) {
        return self.keyActionPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_MASK_TYPE) {
        return self.maskTypePickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_Vibrator){
        return self.vibratorPickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_QValue){
        return self.qValuePickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_Algorithm){
        return self.algorithmPickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_MinQValue){
        return self.qValuePickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_MaxQValue){
        return self.qValuePickerData.count;
    }else if(pickerView.tag == PICKER_VIEW_Default_Link_Profile){
        return self.linkProfilePickerData.count;
    } else if(pickerView.tag == PICKER_VIEW_Link_Profile){
        return self.linkProfilePickerData.count;
    }
    return 0;
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_BUZZER) {
        return [self.buzzerPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_KEY_ACTION) {
        return [self.keyActionPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_MASK_TYPE) {
        return [self.maskTypePickerData objectAtIndex:row];
    } else if(pickerView.tag == PICKER_VIEW_Vibrator){
        return [self.vibratorPickerData objectAtIndex:row];
    }else if(pickerView.tag == PICKER_VIEW_QValue){
        return [self.qValuePickerData objectAtIndex:row];
    } else if(pickerView.tag == PICKER_VIEW_Algorithm){
        return [self.algorithmPickerData objectAtIndex:row];
    } else if(pickerView.tag == PICKER_VIEW_MinQValue){
        return [self.qValuePickerData objectAtIndex:row];
    } else if(pickerView.tag == PICKER_VIEW_MaxQValue){
        return [self.qValuePickerData objectAtIndex:row];
    }else if(pickerView.tag == PICKER_VIEW_Default_Link_Profile){
        return [self.linkProfilePickerData objectAtIndex:row];
    } else if(pickerView.tag == PICKER_VIEW_Link_Profile){
        return [self.linkProfilePickerData objectAtIndex:row];
    }
    return @"None";
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == ALERT_VIEW_INTERVAL_TIME) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            if(value.length == 0){
                value = @"0";
            }
            [self setInventoryTime:value];
        }
    } else if (alertView.tag == ALERT_VIEW_IDLE_TIME) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            if(value.length == 0){
                value = @"0";
            }
            [self setIdleTime:value];
        }
    } else if (alertView.tag == ALERT_VIEW_AUTO_OFF_TIME) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            if(value.length == 0){
                value = @"0";
            }
            [self setAutoOffTime:value];
        }
    } else if (alertView.tag == ALERT_VIEW_BATTERY_INTERVAL) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            
            int checkTime = [value intValue];
            
            if((value.length == 0)|(checkTime<10000)){
                value = @"10000";
            }
            [self setBatteryInterval:value];
        }
    } else if (alertView.tag == ALERT_VIEW_SLEEP_TIME) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            if(value.length == 0){
                value = @"0";
            }
            [self setSleepTime:value];
        }
    } else if (alertView.tag == ALERT_VIEW_THRESHOLD) {
        if (buttonIndex == 1) {
            
            NSString * value = [alertView textFieldAtIndex:0].text;
            
            int checkVal = [value intValue];
            
            
            if(value.length == 0){
                value = @"50";
                
                UIAlertController *alert = [self makeTitleAlert:@"Please enter appropriate ThresholdValue" message:@"Thres Hold' should be greater than or equal 50  and less than or equal 70."];
               [self presentViewController:alert animated:YES completion:nil];
            }
            
            if(checkVal < 50){
                value = @"50";
                UIAlertController *alert = [self makeTitleAlert:@"Please enter appropriate ThresholdValue" message:@"Thres Hold' should be greater than or equal 50."];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
            if(checkVal > 70){
                value = @"70";
                
                UIAlertController *alert = [self makeTitleAlert:@"Please enter appropriate ThresholdValue" message:@"Thres Hold' should be less than or equal 70."];
               [self presentViewController:alert animated:YES completion:nil];
            }
             
            [self setThresHold:value];
        }
    }
    
}

-(UIAlertController*)makeTitleAlert:(NSString*)title message:(NSString *)message{
    
    
    UIAlertController *alert=   [UIAlertController
                                       alertControllerWithTitle:title
                                       message:message
                                       preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* okey = [UIAlertAction
                                       actionWithTitle:@"OK"
                                       style:UIAlertActionStyleDefault
                                       handler:^(UIAlertAction * action){
                  
                  [alert dismissViewControllerAnimated:YES completion:nil];
                  
              }];

    
    [alert addAction:okey];
    return alert;

}



#pragma mark - Getters
- (NSArray *)buzzerPickerData {
    return @[@"Off", @"Low", @"High"];
}
- (NSArray *)vibratorPickerData {
    return @[@"Off", @"On"];
}
- (NSArray *)keyActionPickerData {
    return @[@"Not Used", @"Used"];
}
- (NSArray *)maskTypePickerData {
    return @[@"No Mask",@"Selection Mask", @"EPC Mask"];
}
- (NSArray *)qValuePickerData {
    return @[@"00", @"01",@"02",@"03",@"04",@"05",@"06",@"07",@"08",@"09",@"10",@"11",@"12",@"13",@"14",@"15"];
}
- (NSArray *)linkProfilePickerData{
    return @[@"0",@"1",@"2",@"3"];
}
- (NSArray *)algorithmPickerData{
    return @[@"Fixed Q",@"Dynamic Q"];
}


#pragma mark - Init
- (void)initLbtItemData {
    if (_lbtItemData == nil) {
        
        //_lbtItemData = [systemSetting getLbtItemData];
        NSMutableArray *lbtItems = [[NSMutableArray alloc] initWithArray: appDelegate.mReader.getLBT];
        LbtItem *lbtI = [[LbtItem alloc] init];
        for (LbtItem *lbtItem in lbtItems)
        {
            lbtItem.frequency = [appDelegate.mReader getLBTFrequency:lbtItem.mSlot];
            if ([lbtItem.frequency isEqualToString:@"0 HZ"]) {
                lbtI = lbtItem;
            }
        }
        [lbtItems removeObject:lbtI];
        _lbtItemData = lbtItems;
    }
    
}

#pragma mark - IBAction
- (IBAction)minQValueBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_MinQValue;
    [self.pickerView reloadAllComponents];
    if (![self.minQValueTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.qValuePickerData indexOfObject:self.minQValueTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    self.qValuePickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)maxQValueBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_MaxQValue;
    [self.pickerView reloadAllComponents];
    if (![self.maxQValueTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.qValuePickerData indexOfObject:self.maxQValueTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    self.qValuePickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)qValueBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_QValue;
    [self.pickerView reloadAllComponents];
    if (![self.qValueTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.qValuePickerData indexOfObject:self.qValueTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    self.qValuePickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)algorithmBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_Algorithm;
    [self.pickerView reloadAllComponents];
    if (![self.algorithmTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.algorithmPickerData indexOfObject:self.algorithmTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    self.algorithmPickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)linkProfileBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_Link_Profile;
    [self.pickerView reloadAllComponents];
    if (![self.linkProfileTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.linkProfilePickerData indexOfObject:self.linkProfileTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    self.LinkProfileTableTopView.hidden = NO;
    [self showPickerView];
}



- (IBAction)fwdPWRTHRSHBtnTapped:(id)sender {
//    //#issue 4-2 (Default Link Profile : L251G Not use this function)
//    if(appDelegate.mReader.isAvailableDefaultLinkProfile)
//    {
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Notice !!" message:@"This model does not support the [HST_RFTC_FWDPWRTHRSH] function." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        return;
//    }
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Please enter ThresholdValue" message:@"Default : 50 (MIN = 50 / MAX = 70) " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_THRESHOLD;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
    
}







- (IBAction)buzzerBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_BUZZER;
    [self.pickerView reloadAllComponents];
    
    if (![self.buzzerTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.buzzerPickerData indexOfObject:self.buzzerTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.buzzerPickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)vibratorBtnTapped:(id)sender {
    
    self.pickerView.tag = PICKER_VIEW_Vibrator;
    [self.pickerView reloadAllComponents];
    
    if (![self.vibratorTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.vibratorPickerData indexOfObject:self.vibratorTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.vibratorPickerTopView.hidden = NO;
    [self showPickerView];
}

- (IBAction)inventoryTimeBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Inventory Time:" message:@"Please enter inventory time." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_INTERVAL_TIME;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)idleTimeBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Idle Time:" message:@"Please enter idle time." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_IDLE_TIME;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)autoOffTimeBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Auto Off Time:" message:@"Please enter auto off time." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_AUTO_OFF_TIME;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)keyActionBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_KEY_ACTION;
    [self.pickerView reloadAllComponents];
    
    if (![self.keyActionTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.keyActionPickerData indexOfObject:self.keyActionTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.keyActionPickerTopView.hidden = NO;
    [self showPickerView];
}
- (IBAction)batteryIntervalBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Battery Interval:(Min : 10000ms)" message:@"Please enter battery interval." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_BATTERY_INTERVAL;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)maskTypeBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_MASK_TYPE;
    [self.pickerView reloadAllComponents];
    
    if (![self.maskTypeTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.maskTypePickerData indexOfObject:self.maskTypeTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.maskTypePickerTopView.hidden = NO;
    [self showPickerView];
}

- (IBAction)sleepTimeBtnTapped:(id)sender{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"sleep Time:" message:@"Please enter sleep time." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeNumberPad;
    alert.tag = ALERT_VIEW_SLEEP_TIME;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)saveBtnTapped:(id)sender {
    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    appDelegate.mReader.algorithm = (int) self.algorithmValue;
    appDelegate.mReader.buzzer = self.buzzerValue;
    appDelegate.mReader.vibrator = self.vibratorValue;
    appDelegate.mReader.inventoryTime = (int)self.inventoryTimeValue;
    appDelegate.mReader.idleTime = (int)self.idleTimeValue;
    appDelegate.mReader.autoOffTime = (int)self.autoOffTimeValue;
    appDelegate.mReader.qValue = (int)self.qValue;

    
    appDelegate.mReader.maxQ = (int) self.maxQValue;
    appDelegate.mReader.minQ = (int) self.minQValue;
    appDelegate.mReader.sleepTime = (int) self.sleepTimeValue;
    appDelegate.mReader.maskTypeValue = (int)self.maskTypeValue;
    appDelegate.mReader.thresHoldValue = (int)self.thresHoldValue;
    
    
    
    
    [UserData setBatteryInterval:self.batteryIntervalValue];

    [systemSetting setBuzzer:self.buzzerValue];
    [systemSetting setVibrator:self.vibratorValue];
    [systemSetting setInventoryTime:(int)self.inventoryTimeValue];
    [systemSetting setIdleTime:(int)self.idleTimeValue ];
    [systemSetting setAutoOffTime:(int)self.autoOffTimeValue ];
    [systemSetting setQValue:(int)self.qValue];

    [systemSetting setAlgorithm:(int) self.algorithmValue ];
    [systemSetting setMaxQ:(int) self.maxQValue ];
    [systemSetting setMinQ:(int) self.minQValue ];
    [systemSetting setSleepTime:(int) self.sleepTimeValue ];
    [systemSetting setMaskTypeValue:(int)self.maskTypeValue ];
    [systemSetting setThresHoldValue:(int)self.thresHoldValue ];

    /*robin*/
    [systemSetting setMaskDataUpdate];
    //    [UserData setIsUseKeyAction:self.keyActionValue];
    [AppDelegate dismissGlobalHUD];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Saved successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
- (IBAction)defaultBtnTapped:(id)sender {
    [AppDelegate showGlobalProgressHUDWithTitle:@"Saving..."];
    
    /*Remove all Mask Data*/
    [systemSetting clearAllMaskData];
    
    
    ResultCode res = appDelegate.mReader.defaultParameter;
    if (res != ResultNoError) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Fail" message:@"Set to default failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        
        [alert show];
        return;
    }
    if (isJapan) {
        for (LbtItem *lbtItem in self.lbtItemData) {
            lbtItem.mIsUsed = YES;
        }
        [appDelegate.mReader setLBT:self.lbtItemData];
        [systemSetting setLbtItemData:self.lbtItemData];
    }
    
    self.buzzerValue = appDelegate.mReader.buzzer;
    self.vibratorValue = appDelegate.mReader.vibrator;
    self.inventoryTimeValue = appDelegate.mReader.inventoryTime;
    self.idleTimeValue = appDelegate.mReader.idleTime;
    self.autoOffTimeValue = appDelegate.mReader.autoOffTime;
    self.qValue = appDelegate.mReader.qValue;
    self.maxQValue = appDelegate.mReader.maxQ;
    self.minQValue = appDelegate.mReader.minQ;
    self.sleepTimeValue = appDelegate.mReader.sleepTime;
    self.algorithmValue = appDelegate.mReader.algorithm;
    self.linkProfileValue = appDelegate.mReader.linkProfileValue;
    self.thresHoldValue   = appDelegate.mReader.thresHoldValue;
    self.defaultLinkProfileValue = appDelegate.mReader.defaultLinkProfileValue;
    self.maskTypeValue = MaskType_NO_MASK;
    self.autoOffTimeValue = appDelegate.mReader.autoOffTime;
    appDelegate.mReader.maskTypeValue = MaskType_NO_MASK;
    
    UIApplicationState state = [[UIApplication sharedApplication] applicationState];
    if (state == UIApplicationStateBackground || state == UIApplicationStateInactive)
    {
        [AppDelegate dismissGlobalHUD];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Fail" message:@"Set to default Fail \nPlease retry to default" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    [systemSetting setBuzzer:2];
    [systemSetting setVibrator:1];
    [systemSetting setInventoryTime:400];
    [systemSetting setIdleTime:100];
    [systemSetting setAutoOffTime:600];
    [systemSetting setQValue:4];
    [systemSetting setAlgorithm:1 ];
    [systemSetting setMaxQ:15];
    [systemSetting setMinQ:0];
    [systemSetting setSleepTime:300];
    [systemSetting setMaskTypeValue:0];
    [systemSetting setLinkProfileValue:3];
    [systemSetting setDefaultLinkProfileValue:0];
    [systemSetting setSessionFlag:2];
    [systemSetting setInventorySession:0];
    [systemSetting setOperationTime:0];
    [systemSetting setPowerGain:300];
    [systemSetting setThresHoldValue:50];
    [UserData setBatteryInterval:@"10000"];
    [self initViewData];
    [AppDelegate dismissGlobalHUD];
    
    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Set to default successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
- (IBAction)pickerCloseBtnTapped:(id)sender {
    [self hidePickerView];
}

- (IBAction)qValuePickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    if (self.pickerView.tag == PICKER_VIEW_MaxQValue ) {
        [self setMaxQ:idx];
    } else if (self.pickerView.tag == PICKER_VIEW_MinQValue ) {
        [self setMinQ:idx];
    } else if (self.pickerView.tag == PICKER_VIEW_QValue ) {
        [self setQ:idx];
    }
    [self hidePickerView];
}
- (IBAction)algorithmPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setAlgorithm:idx];
    [self hidePickerView];
}
- (IBAction)linkProfilePickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    if (self.pickerView.tag == PICKER_VIEW_Link_Profile ) {
        [self setLinkProfile:idx];
        appDelegate.mReader.linkProfileValue = (int)self.linkProfileValue;
        [systemSetting setLinkProfileValue:(int)self.linkProfileValue];
    } else if (self.pickerView.tag == PICKER_VIEW_Default_Link_Profile) {
        [self setDefaultLinkProfile:idx];
        appDelegate.mReader.defaultLinkProfileValue = (int)self.defaultLinkProfileValue;
        [systemSetting setDefaultLinkProfileValue:(int)self.defaultLinkProfileValue];
    }
    [self hidePickerView];
}

- (IBAction)buzzerPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setBuzzer:idx];
    [self hidePickerView];
}
- (IBAction)vibratorPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setVibrator:idx];
    [self hidePickerView];
}

- (IBAction)keyActionPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setKeyAction:idx];
    [self hidePickerView];
}
- (IBAction)maskTypePickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setMaskType:idx];
    [self hidePickerView];
}
- (IBAction)lbtChannelBtnTapped:(id)sender {
    //    [AppDelegate showGlobalProgressHUDWithTitle:@"LBT Channel report"];
    //    [CATransaction commit];
    //    [self initLbtItemData];
    //    [AppDelegate dismissGlobalHUD];
    [self.tableView reloadData];
    self.lbtChannelTableTopView.hidden = NO;
    self.tableView.hidden = NO;
    self.shadowView.hidden = NO;
}

- (IBAction)tableCloseBtnTapped:(id)sender {
    [self hideTableView];
}

- (IBAction)lbtChannelTableOkBtnTapped:(id)sender {
    [self hideTableView];
    [appDelegate.mReader setLBT:self.lbtItemData];
    [systemSetting setLbtItemData:self.lbtItemData];
}

#pragma mark - Custom
- (void)showPickerView {
    self.pickerView.hidden = NO;
    self.shadowView.hidden = NO;
}
- (void)hidePickerView {
    self.LinkProfileTableTopView.hidden = YES;
    self.algorithmPickerTopView.hidden = YES;
    self.qValuePickerTopView.hidden = YES;
    self.vibratorPickerTopView.hidden = YES;
    self.buzzerPickerTopView.hidden = YES;
    self.keyActionPickerTopView.hidden = YES;
    self.maskTypePickerTopView.hidden = YES;
    self.pickerView.hidden = YES;
    self.shadowView.hidden = YES;
}
- (void)hideTableView {
    self.lbtChannelTableTopView.hidden = YES;
    self.tableView.hidden = YES;
    self.shadowView.hidden = YES;
}
- (void)setBuzzer:(NSInteger)index {
    self.buzzerTextField.text = [self.buzzerPickerData objectAtIndex:index];
    self.buzzerValue = (int)index;
}
- (void)setVibrator:(NSInteger)index {
    self.vibratorTextField.text = [self.vibratorPickerData objectAtIndex:index];
    self.vibratorValue = (int)index;
}
- (void)setMinQ:(NSInteger)index {
    if (index > self.maxQValue) {
        index = self.maxQValue;
    }
    self.minQValueTextField.text = [self.qValuePickerData objectAtIndex:index];
    self.minQValue = (int)index;
}
- (void)setMaxQ:(NSInteger)index {
    if (index < self.minQValue) {
        index = self.minQValue;
    }
    self.maxQValueTextField.text = [self.qValuePickerData objectAtIndex:index];
    self.maxQValue = (int)index;
}

- (void)setLinkProfile:(NSInteger)index{
    self.linkProfileTextField.text = [self.linkProfilePickerData objectAtIndex:index];
    self.linkProfileValue = index;
}

- (void)setDefaultLinkProfile:(NSInteger)index{
    self.defaultLinkProfileTextField.text = [self.linkProfilePickerData objectAtIndex:index];
    self.defaultLinkProfileValue = index;
}

- (void)setQ:(NSInteger)index {
    self.qValueTextField.text = [self.qValuePickerData objectAtIndex:index];
    self.qValue = (int)index;
}
- (void)setAlgorithm:(NSInteger)index {
    self.algorithmTextField.text = [self.algorithmPickerData objectAtIndex:index];
    self.algorithmValue = (int)index;
}
- (void)setInventoryTime:(NSString *)inventoryTime {
    self.inventoryTimeTextField.text = inventoryTime;
    self.inventoryTimeValue = [inventoryTime integerValue];
}
- (void)setIdleTime:(NSString *)idleTime {
    self.idleTimeTextField.text = idleTime;
    self.idleTimeValue = [idleTime integerValue];
}
- (void)setAutoOffTime:(NSString *)autoOffTime {
    self.autoOffTimeTextField.text = autoOffTime;
    self.autoOffTimeValue = [autoOffTime integerValue];
}
- (void)setKeyAction:(NSInteger)index {
    self.keyActionTextField.text = [self.keyActionPickerData objectAtIndex:index];
    self.keyActionValue = index;
    
}
- (void)setBatteryInterval:(NSString *)batteryInterval {
    self.batteryIntervalTextField.text = batteryInterval;
    self.batteryIntervalValue = batteryInterval;
}
- (void)setSleepTime:(NSString *)sleepTime {
    self.sleepTimeTextField.text = sleepTime;
    self.sleepTimeValue = [sleepTime integerValue];
}
- (void)setMaskType:(NSInteger)index {
    self.maskTypeTextField.text = [self.maskTypePickerData objectAtIndex:index];
    self.maskTypeValue = (int)index;
}

-(void)setThresHold:(NSString *)threshold {
    self.thresHoldTextField.text = threshold;
    self.thresHoldValue = [threshold integerValue];
}

- (void)initViewData {
    [self setMaxQ:self.maxQValue];
    [self setMinQ:self.minQValue];
    [self setMaskType:self.maskTypeValue];
    [self setLinkProfile:self.linkProfileValue];
    [self setDefaultLinkProfile:self.defaultLinkProfileValue];
    self.linkProfileTextField.text  = [NSString stringWithFormat:@"%ld",(long)self.linkProfileValue];
    [self setAlgorithm:self.algorithmValue];
    [self setQ:self.qValue];
    [self setBuzzer:self.buzzerValue];
    [self setVibrator:self.vibratorValue];
    [self setInventoryTime:[NSString stringWithFormat:@"%ld", (long)self.inventoryTimeValue]];
    [self setIdleTime:[NSString stringWithFormat:@"%ld", (long)self.idleTimeValue]];
    [self setAutoOffTime:[NSString stringWithFormat:@"%ld", (long)self.autoOffTimeValue]];
    [self setSleepTime:[NSString stringWithFormat:@"%ld", (long)self.sleepTimeValue]];
    [self setThresHold:[NSString stringWithFormat:@"%ld", (long)self.thresHoldValue]];
    NSString *batteryInterval = [UserData getBatteryInterval];
    [self setBatteryInterval:batteryInterval];
}

#pragma mark - NSNotification 673834852
- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = nil;
        [self hideTableView];
        [self hidePickerView];
        [self.navigationController popToRootViewControllerAnimated:YES];
    });
}

- (void)AsReaderGUNConnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = [[AsReader alloc] initWithAsReaderGUN:appDelegate.mAsReaderGUN delegate:self];
        
    });
}


#pragma mark - Reader Event Handler Methods
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
    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) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Failed to get response. Try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        
        [self.navigationController popViewControllerAnimated:YES];
    }
}
@end
