//
//  BarcodeOption_VC.m
//  AsReaderLR
//
//  Created by mac on 2017/6/19.
//  Copyright © 2017年 asterisk. All rights reserved.
//

#import "BarcodeOption_VC.h"
#import "UserData.h"
#import "SystemSetting.h"
#define PICKER_VIEW_BUZZER          0
#define PICKER_VIEW_Vibrator        1

#define ALERT_VIEW_BATTERY_INTERVAL 10
#define ALERT_VIEW_SLEEP_TIME       11

@interface BarcodeOption_VC ()

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UITextField *buzzerTextField;
@property (weak, nonatomic) IBOutlet UITextField *vibratorTextField;
@property (weak, nonatomic) IBOutlet UITextField *batteryIntervalTextField;
@property (weak, nonatomic) IBOutlet UIView *buzzerPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *vibratorPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *shadowView;
@property (strong, nonatomic) NSArray *buzzerPickerData;
@property (strong, nonatomic) NSArray *vibratorPickerData;
@property (readwrite, nonatomic) BuzzerState buzzerValue;
@property (readwrite, nonatomic) VibratorState vibratorValue;
@property (strong, nonatomic) NSString *batteryIntervalValue;
@property (weak, nonatomic) IBOutlet UITextField *sleepTimeTextField;
@property (readwrite, nonatomic) NSInteger sleepTimeValue;

@end

@implementation BarcodeOption_VC{
    SystemSetting * systemSetting;
}

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


- (void)viewWillAppear:(BOOL)animated {
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" 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.sleepTimeValue = appDelegate.mReader.sleepTime;
    [self initViewData];
    [self.navigationController.view addSubview:self.shadowView];
    [AppDelegate dismissGlobalHUD];
}

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

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


#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_Vibrator){
        return self.vibratorPickerData.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_Vibrator){
        return [self.vibratorPickerData objectAtIndex:row];
    }
    return @"None";
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString * text = [alertView textFieldAtIndex:0].text;
    if (text.length == 0) {
        text =@"0";
    }
    if (alertView.tag == ALERT_VIEW_BATTERY_INTERVAL) {
        if (buttonIndex == 1) {
           
            [self setBatteryInterval:text];
        }
    } else if (alertView.tag == ALERT_VIEW_SLEEP_TIME) {
        if (buttonIndex == 1) {
            [self setSleepTime:text];
        }
    }
    
}
#pragma mark - Getters
- (NSArray *)buzzerPickerData {
    return @[@"Off", @"Low", @"High"];
}
- (NSArray *)vibratorPickerData {
    return @[@"Off", @"On"];
}

#pragma mark - IBAction
 - (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)batteryIntervalBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Battery Interval:" 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)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.mReader.buzzer = self.buzzerValue;
    appDelegate.mReader.vibrator = self.vibratorValue;
    appDelegate.mReader.sleepTime = (int) self.sleepTimeValue;
    
    [systemSetting setBuzzer:self.buzzerValue];
    [systemSetting setVibrator:self.vibratorValue];
    [systemSetting setSleepTime:(int)self.sleepTimeValue];

    [UserData setBatteryInterval:self.batteryIntervalValue];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Saved successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alert show];
}
- (IBAction)defaultBtnTapped:(id)sender {
    appDelegate.mReader.buzzer = Buzzer_High;
    appDelegate.mReader.vibrator = Vibrator_On;
    appDelegate.mReader.sleepTime = 300;
    
    self.buzzerValue = appDelegate.mReader.buzzer;
    self.vibratorValue = appDelegate.mReader.vibrator;
    self.sleepTimeValue = appDelegate.mReader.sleepTime;
    
    [systemSetting setBuzzer:self.buzzerValue];
    [systemSetting setVibrator:self.vibratorValue];
    [systemSetting setSleepTime:(int)self.sleepTimeValue];
    
    [UserData setBatteryInterval:@"10000"];
    [self initViewData];
    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)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)tableCloseBtnTapped:(id)sender {
    [self hideTableView];
}

#pragma mark - Custom
- (void)showPickerView {
    self.pickerView.hidden = NO;
    self.shadowView.hidden = NO;
}
- (void)hidePickerView {
    self.vibratorPickerTopView.hidden = YES;
    self.buzzerPickerTopView.hidden = YES;
    self.pickerView.hidden = YES;
    self.shadowView.hidden = YES;
}
- (void)hideTableView {
    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)setBatteryInterval:(NSString *)batteryInterval {
    self.batteryIntervalTextField.text = batteryInterval;
    self.batteryIntervalValue = batteryInterval;
}
- (void)setSleepTime:(NSString *)sleepTime {
    self.sleepTimeTextField.text = sleepTime;
    self.sleepTimeValue = [sleepTime integerValue];
}

- (void)initViewData {
    [self setBuzzer:self.buzzerValue];
    [self setVibrator:self.vibratorValue];
    [self setSleepTime:[NSString stringWithFormat:@"%ld", (long)self.sleepTimeValue]];
    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];
    });
}
#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
