#import "MainViewController.h"
#import "MainButton.h"
#import "UserData.h"
#import <AsReaderGunSDK/AsReaderGunSDK.h>
#import <AsRingAccessorySDK/AsRingDeviceSDK.h>
#import "VersionHandler.h"
#import "SystemSetting.h"
#define BATTERY_NONE            0
#define BATTERY_QUARTER         1
#define BATTERY_HALF            2
#define BATTERY_THIRD_QUARTER   3
#define BATTERY_FULL            4
#define BATTERY_NODATA          5


#define CONNECTION_OFF          0
#define CONNECTION_ON           1

@interface MainViewController ()<AsRingDeviceSDKDelegate, AsReaderDelegate,UITextFieldDelegate,VersionHandlerDelegate>
{
    UIBarButtonItem *searchBarButtonItem;
    UITapGestureRecognizer *logoDebugTap;
    AsRingDeviceSDK *asRingDeviceSDK;
    UIView * backView;
    NSString *updateUrl;
    NSTimer *batteryCheckTimer;
}
@property (weak, nonatomic) IBOutlet UILabel *asRingPlusVersion;

@property (weak, nonatomic) IBOutlet MainButton *btnInventory;
@property (strong, nonatomic) IBOutletCollection(MainButton) NSArray *buttonCollection;
@property (weak, nonatomic) IBOutlet UIImageView *batteryImage;
@property (weak, nonatomic) IBOutlet UITextField *vibratorTextField;
@property (weak, nonatomic) IBOutlet UITextField *buzzerTextField;
@property (weak, nonatomic) IBOutlet UIButton *buzzerButton;
@property (weak, nonatomic) IBOutlet UIButton *vibratorButton;
@property (weak, nonatomic) IBOutlet UIButton *ledTestButton;
@property (weak, nonatomic) IBOutlet UIImageView *logoImage;
@property (weak, nonatomic) IBOutlet UILabel *labelDemoVer;
@property (weak, nonatomic) IBOutlet UILabel *labelFirmwareVer;
@property (weak, nonatomic) IBOutlet UILabel *labelAddress;
@property (weak, nonatomic) IBOutlet UILabel *labelSDKVer;
@property (strong, nonatomic) NSMutableArray *mAsRingMap;
@property (weak, nonatomic) IBOutlet UILabel *regionLabel;
@property (weak, nonatomic) IBOutlet UILabel *snLabel;
@property (weak, nonatomic) IBOutlet UILabel *ufVersion;
@property (weak, nonatomic) IBOutlet UIScrollView *mainScrollView;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.mAsReaderGUN = [[AsReaderGUN alloc]initWithDeviceModel:@"com.asreader.gun"];
    appDelegate.mAsReaderGUN.deviceModel = @"com.asreader.gun";
    NSLog(@"App Version : %@", appDelegate.getAppVersion);
    self.labelDemoVer.text = appDelegate.getAppVersion;
    self.regionLabel.text = @"";
    self.snLabel.text = @"";
    self.ufVersion.text = @"";
    self.labelSDKVer.text = appDelegate.mAsReaderGUN.getAsReaderGUNVersion;
    self.mainScrollView.contentSize = CGSizeMake(0, self.view.frame.size.height);
    self.mainScrollView.showsVerticalScrollIndicator = NO;
    searchBarButtonItem = self.navigationItem.rightBarButtonItem;
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    /*Robin Test */
    [center addObserver:self selector:@selector(showAlert:) name:@"ShowAlert" object:nil];
    
    /*End Robin*/
    logoDebugTap = nil;
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [VersionHandler sharedVersionHandler].versionHandlerDelegate=self;
        [[VersionHandler sharedVersionHandler] getServeVersionWithUrl:@"https://www.asteriskweb.jp/mrxapp/AsReaderLR/manifest.plist"];
    });
    self.buzzerTextField.text =[NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getBuzzerTime]];
    self.vibratorTextField.text = [NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getVibratorTime]];
    self.buzzerTextField.delegate = self;
    self.vibratorTextField.delegate = self;
    backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor grayColor];
    backView.alpha = 0.5;
    backView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    [self.mainScrollView setContentOffset:CGPointMake(0,0) animated:YES];
}

-(void)showAlert:(NSNotification*) notification
{
    NSString *errMessage = [[notification userInfo] objectForKey:@"DATA"];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Confirm" message:errMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNConnected:) name:@"AsReaderGUNConnected" object:nil];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    [center addObserver:self selector:@selector(showAlert:) name:@"ShowAlert" object:nil];
    UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    tapGestureRecognizer.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGestureRecognizer];
}


- (void) keyboardHide : (NSNotification*)notification {
    self.mainScrollView.scrollEnabled = YES;
    [backView removeFromSuperview];
    [self.vibratorTextField resignFirstResponder];
    [self.buzzerTextField resignFirstResponder];
    if ([self.buzzerTextField.text intValue] == 0) {
        self.buzzerTextField.text = @"1";
    }
    if ( [self.buzzerTextField.text intValue]  >= 5000) {
        self.buzzerTextField.text = @"4999";
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Buzzer Value" message:@"Please enter the value (1~4999)"  preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:actionCancel];
        [self.navigationController presentViewController:alertController animated:NO completion:nil];
    }
    if ([self.vibratorTextField.text intValue] == 0) {
        self.vibratorTextField.text = @"1";
    }
    if ( [self.vibratorTextField.text intValue]  >= 5000) {
        self.vibratorTextField.text = @"4999";
        
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Vibrator Value" message:@"Please enter the value (1~4999)"  preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction * actionCancel = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:actionCancel];
        [self.navigationController presentViewController:alertController animated:NO completion:nil];
    }
    [[SystemSetting sharedSystemSetting] setVibratorTime:[self.vibratorTextField.text intValue]];
    [[SystemSetting sharedSystemSetting] setBuzzerTime:[self.buzzerTextField.text intValue]];
    [self.mainScrollView setContentOffset:CGPointMake(0,100) animated:YES];
}
- (void)viewDidAppear:(BOOL)animated{
    
   
    [self changeBatteryImage:BATTERY_NODATA];
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)])
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    
    if (appDelegate.mReader != nil) {
        self.asRingPlusVersion.text = [[AsRingDeviceSDK sharedAsRingDeviceSDK] getAsRingFirmwareRevision];
        [appDelegate.mReader setDelegate:self];
        self.labelFirmwareVer.text = appDelegate.mReader.firmwareVersion;
        self.labelAddress.text = appDelegate.mReader.mAsReaderGUN.address;
        //int batteryStatus = appDelegate.mReader.batteryStatus;
        //[self changeBatteryImage:batteryStatus];
//        [self enableAllButtons];
//        if (!appDelegate.mReader.isBarcodeModule) {
//            [self disableBarcodeButtons];
//        }
//        if (!appDelegate.mReader.isRFIDModule) {
//            [self disableRFIDButtons];
//        }
        [self startMonitoringBattery:NO];
        self.regionLabel.text = [appDelegate.mReader regionName];
        self.snLabel.text = [appDelegate.mReader serialNumber];
        self.ufVersion.text = [appDelegate.mReader rFModuleVersion];
        
        [[SystemSetting sharedSystemSetting] asReaderGUNSetting];
        [AppDelegate dismissGlobalHUD];
        
        /*Robin*/
        [appDelegate.mReader setScanMode:RFIDScanMode];
        /*End Robin*/
        
    }else{
        [self disableAllUIs];
    }
}
- (void)startMonitoringBattery:(BOOL)isStart
{
    [self updateBattery];
    float periodicTime = [[UserData getBatteryInterval]intValue]/1000.0;
    
    if(batteryCheckTimer!=nil)
    {
        [batteryCheckTimer invalidate];
        batteryCheckTimer = nil;
    }
    
    if(isStart)
         batteryCheckTimer = [NSTimer scheduledTimerWithTimeInterval:periodicTime target:self selector:@selector(updateBattery) userInfo:nil repeats:YES];
    
}

-(void)updateBattery
{
    int batteryStatus = appDelegate.mReader.batteryStatus;
    [self changeBatteryImage:batteryStatus];
}



- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNConnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
    /*Robin Error Alarm*/
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"ShowAlert" object:nil];
    [self startMonitoringBattery:NO];
    [AppDelegate dismissGlobalHUD];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


#pragma mark - Navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
}

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

#pragma mark - Connect/Disconnect Peripheral Methods
- (void)disconnectDevice {
    if (appDelegate.mReader != nil) {
        [appDelegate.mReader disconnect];
    }
    appDelegate.mReader = nil;
    [self disableAllUIs];
}

#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)readerInitialized:(AsReader *)reader {
    
    NSLog(@"readerInitialized");
    [AppDelegate showGlobalProgressHUDWithTitle:@"Barcode Setting..."];
    [CATransaction commit];
    [[SystemSetting sharedSystemSetting] barcodeSetting];
    [AppDelegate dismissGlobalHUD];
    [CATransaction commit];
    
    
    [AppDelegate showGlobalProgressHUDWithTitle:@"RFID Setting..."];
    [CATransaction commit];
    [[SystemSetting sharedSystemSetting] RFIDSetting];
    [AppDelegate dismissGlobalHUD];
    [CATransaction commit];
    
    
    [self enableAllButtons];
    
    if (!appDelegate.mReader.isBarcodeModule) {
        [self disableBarcodeButtons];
    }else{
       
    }
    if (!appDelegate.mReader.isRFIDModule) {
        [self disableRFIDButtons];
    }else{
      
    }
}

- (void)updateDeviceState:(ResultCode)error {
    //    NSLog(@"MV - updateDeviceState");
    if (error != ResultNoError) {
        NSString * message = @"";
        NSString * title  = @"";
        title   = @"AsRingDevice";
        message = @"AsRing device is not available on this device";
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert setTag:kDeviceAlertView];
        
    }
}


- (void)readTag:(NSString *)tag rssi:(float)rssi phase:(float)phase {
    
}

- (void)changedActionState:(CommandType)action resultCode:(NSInteger)resultCode {
    //    NSLog(@"MV - changedActionState");
    [self enableControlByActionState];
}

- (void)enableControlByActionState {
    
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    switch ([alertView tag]) {
        case kBluetoothAlertView:
            break;
        case kDeviceAlertView:
            if (appDelegate.mReader != nil) {
                appDelegate.mReader = nil;
            } else {
                [self disconnectDevice];
            }
            break;
        case VersionAlertView:
            if (buttonIndex==0) {
                
            }else{
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:updateUrl] options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }
            break;
        case VersionForceAlertView:
            if (buttonIndex==0) {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:updateUrl] options:@{} completionHandler:^(BOOL success) {
                    
                }];
            }else{
                
            }
            break;
        default:
            break;
    }
}

#pragma mark - Custom
- (void)enableAllButtons {
    
    for (MainButton *btn in self.buttonCollection) {
        [btn enableButton];
    }
    [self startMonitoringBattery:YES];
    [self changeLogoImage:CONNECTION_ON];
    [self.buzzerButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.vibratorButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    self.buzzerTextField.text =[NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getBuzzerTime]];
    self.vibratorTextField.text = [NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getVibratorTime]];
    
    [self.buzzerTextField setEnabled:YES];
    [self.vibratorTextField setEnabled:YES];
    [self.buzzerButton setEnabled:YES];
    [self.vibratorButton setEnabled:YES];
    [self.ledTestButton setEnabled:YES];
}

- (void)disableAllUIs {
    [self startMonitoringBattery:NO];
    [self keyboardHide:nil];
    [self.mainScrollView setContentOffset:CGPointMake(0,0) animated:YES];
    self.asRingPlusVersion.text = @"";
    self.labelFirmwareVer.text = @"";
    self.labelAddress.text = @"";
    self.regionLabel.text = @"";
    self.snLabel.text = @"";
    self.ufVersion.text = @"";
    
    [self.buzzerButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.vibratorButton setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    self.buzzerTextField.text = [NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getBuzzerTime]];
    self.vibratorTextField.text = [NSString stringWithFormat:@"%d",[[SystemSetting sharedSystemSetting] getVibratorTime]];
    [self.buzzerTextField setEnabled:NO];
    [self.vibratorTextField setEnabled:NO];
    [self.buzzerButton setEnabled:NO];
    [self.vibratorButton setEnabled:NO];
    [self.ledTestButton setEnabled:NO];
    
    for (MainButton *btn in self.buttonCollection) {
        [btn disableButton];
    }
    [self changeBatteryImage:BATTERY_NODATA];
    [self changeLogoImage:CONNECTION_OFF];
    
    [self rightBarButtonDisconnected];
    
}

- (void)disableBarcodeButtons {
    [[self.buttonCollection objectAtIndex:6] disableButton];
    [[self.buttonCollection objectAtIndex:7] disableButton];
}

- (void)disableRFIDButtons {
    [[self.buttonCollection objectAtIndex:0] disableButton];
    [[self.buttonCollection objectAtIndex:1] disableButton];
    [[self.buttonCollection objectAtIndex:2] disableButton];
    [[self.buttonCollection objectAtIndex:3] disableButton];
    [[self.buttonCollection objectAtIndex:4] disableButton];
    [[self.buttonCollection objectAtIndex:5] disableButton];
    [[self.buttonCollection objectAtIndex:8] disableButton];
}
- (void)changeBatteryImage:(NSUInteger)batteryStatus {
    if (batteryStatus == BATTERY_NONE) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery0"]];
    } else if (batteryStatus == BATTERY_QUARTER) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery1"]];
    } else if (batteryStatus == BATTERY_HALF) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery2"]];
    } else if (batteryStatus == BATTERY_THIRD_QUARTER) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery3"]];
    } else if (batteryStatus == BATTERY_FULL) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery4"]];
    } else if (batteryStatus == BATTERY_NODATA) {
        [self.batteryImage setImage:[UIImage imageNamed:@"battery"]];
    }
    
    
}

- (void)changeLogoImage:(NSUInteger)connectionStatus {
    if (connectionStatus == CONNECTION_OFF) {
        [self.logoImage setImage:[UIImage imageNamed:@"asreader_logo_off"]];
        
        if(logoDebugTap != nil)
        {
            [self.logoImage setUserInteractionEnabled:NO];
            [self.logoImage removeGestureRecognizer:logoDebugTap];
            logoDebugTap = nil;
        }
    } else if (connectionStatus == CONNECTION_ON) {
        [self.logoImage setImage:[UIImage imageNamed:@"asreader_logo_on"]];
        if(logoDebugTap != nil)
        {
            logoDebugTap = nil;
        }
        logoDebugTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(logoDebugTapDetected:)];
        logoDebugTap.numberOfTapsRequired = 5;
        [self.logoImage setUserInteractionEnabled:YES];
        [self.logoImage addGestureRecognizer:logoDebugTap];
    }
}

- (void)barButtonItemTapped:(id)sender {
    [self disconnectDevice];
}


- (void)rightBarButtonDisconnected {
    self.navigationItem.rightBarButtonItem = searchBarButtonItem;
}


- (void)accessResult:(ResultCode)error actionState:(CommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase  frequency:(float)frequency{
    if (error != ResultNoError) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:[AsResultCode msg:error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        return;
    }
}

#pragma mark - NSNotification
- (void)AsReaderGUNDisconnected:(NSNotification *)notification {
    NSLog(@"%s", __PRETTY_FUNCTION__);
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"Loading Hide...");
        appDelegate.mReader = nil;
        [self disableAllUIs];
        [AppDelegate dismissGlobalHUD];
    });
}
- (IBAction)clickActionSheet:(UIBarButtonItem *)sender {
    
}

- (IBAction)clickLastBTConnect:(UIBarButtonItem *)sender {
    
}

-(void)logoDebugTapDetected:(UITapGestureRecognizer *)sender
{
    if (sender.state == UIGestureRecognizerStateEnded)
    {
        UIActionSheet * actionSheet = [[UIActionSheet alloc] initWithTitle:@"Please select the operationg mode."
                                                                  delegate:self
                                                         cancelButtonTitle:@"Debug Mode"
                                                    destructiveButtonTitle:@"Normal Mode"
                                                         otherButtonTitles:nil];
        actionSheet.tag = 200;
        [actionSheet showInView:self.view];
    }
}
#pragma mark VersionHandlerDelegate methods
- (void)UpdateUrl:(NSString *)url forceType:(NSString *)forceType{
    dispatch_async(dispatch_get_main_queue(), ^{
        updateUrl=url;
        if ([forceType isEqualToString:@"0"]) {
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"There is a new version of the Application server, please go to update the latest Application server" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Update", nil];
            [alert setTag:VersionAlertView];
            [alert show];
        }else{
            UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Warning" message:@"Your Application version is too old, it is necessary to update the latest version of the Application server" delegate:self cancelButtonTitle:@"Update" otherButtonTitles:nil, nil];
            [alert setTag:VersionForceAlertView];
            [alert show];
        }
    });
}

#pragma mark UIActionSheetDelegate methods
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([actionSheet tag] == 200)
    {
        if (buttonIndex == 0 )
        {
            [appDelegate.mReader setDebugMode:NO];
        }
        else
        {
            [appDelegate.mReader setDebugMode:YES];
        }
    }
    
}

- (void)AsReaderGUNConnected:(NSNotification *)notification {
    dispatch_async(dispatch_get_main_queue(), ^{
        appDelegate.mReader = [[AsReader alloc] initWithAsReaderGUN:appDelegate.mAsReaderGUN delegate:self.readerDelegate];
        [self viewDidAppear:YES];
    });
}
- (IBAction)onClickVibratorButton:(id)sender {
    if ([self.vibratorTextField.text intValue] > 0 && [self.vibratorTextField.text intValue] < 5000 ) {
        [[SystemSetting sharedSystemSetting] setVibratorTime:[self.vibratorTextField.text intValue]];
        ResultCode  rCode = [appDelegate.mReader startVibratorWithVibratorTime:[self.vibratorTextField.text intValue]];
        if (rCode == ResultOperationFailed) {
            NSLog(@"Vibrator Start ERROR!");
        }
    }else{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Vibrator Value" message:@"Please enter the value (1~4999)" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

- (IBAction)onClickBuzzerButton:(id)sender {
    if ([self.buzzerTextField.text intValue] > 0 && [self.buzzerTextField.text intValue] < 5000 ) {
        [[SystemSetting sharedSystemSetting] setBuzzerTime:[self.buzzerTextField.text intValue]];
        ResultCode  rCode = [appDelegate.mReader startBuzzerWithBuzzerTime:[self.buzzerTextField.text intValue]];
        if (rCode == ResultOperationFailed) {
            NSLog(@"Buzzer Start ERROR!");
        }
    }else{
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Buzzer Value" message:@"Please enter the value (1~4999)" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    self.mainScrollView.scrollEnabled = NO;
    [self.view addSubview:backView];
    if ([self.buzzerTextField isFirstResponder]) {
        self.buzzerTextField.keyboardType = UIKeyboardTypeNumberPad;
    }else if ([self.vibratorTextField isFirstResponder]) {
        self.vibratorTextField.keyboardType = UIKeyboardTypeNumberPad;
    }
    [self.mainScrollView setContentOffset:CGPointMake(0,260) animated:YES];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([[textField.text stringByAppendingString:string]intValue] <= 0) {
        textField.text = @"1";
    }
    return YES;
}

/*Robin*/ //For Testing
-(IBAction)btnModeLedTestActon:(id)sender
{
    // create an alert controller
    UIAlertController *alertModeLedTest = [UIAlertController alertControllerWithTitle:@"MODE LED TEST" message:@"\n\n\n\n\n\n" preferredStyle:UIAlertControllerStyleAlert];

    // create the actions handled by each button
    UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

    }];

    [alertModeLedTest addAction:actionOK];

    // Establish the weak self reference
    __weak typeof(self) weakSelf = self;
    
    // Create button
    UILabel *labelLeft  = [[UILabel alloc]initWithFrame:CGRectMake(5 , 50, 200, 50)];
   
    UILabel *labelRight = [[UILabel alloc]initWithFrame:CGRectMake(5 , 100, 200, 50)];
    [labelLeft  setText:@" LEFT LED (ON/OFF)"];
    [labelRight setText:@" RIGHT LED (ON/OFF)"];
    
    UISwitch *switchLeft = [[UISwitch alloc]init];
    [switchLeft setFrame:CGRectMake(200 , 60, 0, 0)];  // Not sure about size
    [switchLeft setTag:1];
    [switchLeft addTarget:weakSelf action:@selector(changeModeLedTestAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UISwitch *switchRight = [[UISwitch alloc]init];
    [switchRight setFrame:CGRectMake(200 , 110, 0, 0)];  // Not sure about size
    [switchRight setTag:2];
    [switchRight addTarget:weakSelf action:@selector(changeModeLedTestAction:) forControlEvents:UIControlEventTouchUpInside];
    [switchLeft  setOn:appDelegate.mReader.modeLeftLedOn];
    [switchRight setOn:appDelegate.mReader.modeRightLedOn];
    
    
    // Setup image for button
    [alertModeLedTest.view addSubview:switchLeft];
    [alertModeLedTest.view addSubview:switchRight];
    [alertModeLedTest.view addSubview:labelLeft];
    [alertModeLedTest.view addSubview:labelRight];
    
    [self presentViewController:alertModeLedTest animated:YES completion:nil];
    
}

-(void)changeModeLedTestAction:(UISwitch*)sender {
    
    int tagId = (int)sender.tag;
    UISwitch *sw = (UISwitch *)sender;
    
    switch (tagId) {
        case 1: //LEFT
            if(sw.isOn)
                appDelegate.mReader.modeLeftLedOn = YES;
            else
                appDelegate.mReader.modeLeftLedOn = NO;
            break;
            
        case 2: //RIGHT
            if(sw.isOn)
                appDelegate.mReader.modeRightLedOn = YES;
            else
                appDelegate.mReader.modeRightLedOn = NO;
               
            break;
            
        default:
            break;
    }
    
    
}


@end

