#define PICKER_VIEW_POWER_GAIN  0

#define ALERT_VIEW_PASSWORD         0
#define ALERT_VIEW_OPERATION_TIME   1
#define ALERT_VIEW_SET_ACCESS_PW    2
#define ALERT_VIEW_SET_KILL_PW      3
#define ALERT_VIEW_KILL_PW          4
#define ALERT_VIEW_LOCK             5

#define ALERT_VIEW_OUTHERVIEW       30



#define MSG_TAG_WAIT        @"Tag memory to lock or kill,\nPlease click the button"

#import "TagAccessViewController.h"
#import "AppDelegate.h"
#import "UserData.h"
#import "SystemSetting.h"
@interface TagAccessViewController () {
    AppDelegate *appDelegate;
    UIAlertView *currentAlertView;
    BOOL isActionResult;
    MaskType maskType;
    SystemSetting * systemSetting;
}
@property (weak, nonatomic) IBOutlet UILabel *selectionTagLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UISwitch *killPasswordSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *accessPasswordSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *epcSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *tidSwitch;
@property (weak, nonatomic) IBOutlet UISwitch *userSwitch;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *powerGainTextField;
@property (weak, nonatomic) IBOutlet UITextField *operationTimeTextField;
@property (weak, nonatomic) IBOutlet UIButton *lockBtn;
@property (weak, nonatomic) IBOutlet UIButton *unlockBtn;
@property (weak, nonatomic) IBOutlet UIButton *permalockBtn;
@property (weak, nonatomic) IBOutlet UIButton *killBtn;
@property (weak, nonatomic) IBOutlet UIButton *setAccessPwdBtn;
@property (weak, nonatomic) IBOutlet UIButton *setKillPwdBtn;
@property (weak, nonatomic) IBOutlet UIButton *clearBtn;
@property (weak, nonatomic) IBOutlet UIButton *maskBtn;
@property (weak, nonatomic) IBOutlet UIView *powerGainPickerTopView;
@property (strong, nonatomic) NSArray *powerGainPickerData;
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *buttonCollection;
@property (weak, nonatomic) IBOutlet UILabel *rssiLabel;
@property (weak, nonatomic) IBOutlet UILabel *phaseLabel;
@property (weak, nonatomic) IBOutlet UISwitch *reportRssiSwitch;
@property (strong, nonatomic) IBOutletCollection(UILabel) NSArray *reportRssiCollection;

@end

@implementation TagAccessViewController

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

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(AsReaderGUNDisconnected:) name:@"AsReaderGUNDisconnected" object:nil];
    [center addObserver:self selector:@selector(AsReaderGUNConnected:) name:@"AsReaderGUNConnected" object:nil];
    [appDelegate.mReader setDelegate:self];
}
- (void)viewDidAppear:(BOOL)animated{
    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.mReader setDelegate:self];
    
    if (appDelegate.mReader == nil) {
        [AppDelegate dismissGlobalHUD];
        return;
    }
    
    [self initPowerGainPickerData];
    
    int nPower = appDelegate.mReader.powerGain;
    NSInteger operationTime = appDelegate.mReader.operationTime;
    
    appDelegate.mReader.continuousMode = NO;

    BOOL isReportRSSI = appDelegate.mReader.rssiMode;
    maskType = appDelegate.mReader.maskTypeValue;

    if (_maskValue != nil) {
        [appDelegate initMask:_maskValue maskType:MaskType_Selection];
    }
    
    isActionResult = NO;
    
    [self setPowerGain:(int)(nPower / 10)];
    [self setOperationTime:[NSString stringWithFormat:@"%ld", (long)operationTime]];
    [self setReportRssiModeEnabled:isReportRSSI];
    [self.pickerView reloadAllComponents];
    
    if (_maskValue != nil) {
        self.selectionTagLabel.text = _maskValue;
        self.maskBtn.enabled = NO;
    }
    
    [AppDelegate dismissGlobalHUD];
}

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

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


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

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

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

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

        }
    } else if (alertView.tag == ALERT_VIEW_PASSWORD) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            [self setPassword:value];
        }
    } else if (alertView.tag == ALERT_VIEW_SET_ACCESS_PW) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
            [appDelegate.mReader writeMemory:Bank_Reserved offset:2 value:value];
        }
    } else if (alertView.tag == ALERT_VIEW_SET_KILL_PW) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
            [appDelegate.mReader writeMemory:Bank_Reserved offset:0 value:value];
        }
    } else if (alertView.tag == ALERT_VIEW_KILL_PW) {
        if (buttonIndex == 1) {
            NSString * pwd = [alertView textFieldAtIndex:0].text;
            if (pwd && pwd.length != 8) {
                [currentAlertView dismissWithClickedButtonIndex:0 animated:YES];
                currentAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Password length is not valid " delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
                currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
                [currentAlertView show];
                return;
            }else{
                [appDelegate.mReader kill:pwd];
            }
        }
    } else if (alertView.tag == ALERT_VIEW_LOCK) {
        [self stopAction];
    }
}

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

#pragma mark - Getters

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

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

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

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

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

- (IBAction)lockBtnTapped:(id)sender {
    isActionResult = NO;
    
    [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
    
    LockParam *param = [[LockParam alloc] init];
    param.killPassword = [self.killPasswordSwitch isOn];
    param.accessPassword = [self.accessPasswordSwitch isOn];
    param.epc = [self.epcSwitch isOn];
    param.tid = [self.tidSwitch isOn];
    param.user = [self.userSwitch isOn];
    
    int time = [self.operationTimeTextField.text intValue];
    
    [appDelegate.mReader setOperationTime:time];
    [systemSetting setOperationTime:time];

    if ([appDelegate.mReader lock:param] != ResultNoError) {
        NSLog(@"ERROR. Failed to start lock tag");
    };
}
- (IBAction)unlockBtnTapped:(id)sender {
    isActionResult = NO;
    
    [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
    
    LockParam *param = [[LockParam alloc] init];
    param.killPassword = [self.killPasswordSwitch isOn];
    param.accessPassword = [self.accessPasswordSwitch isOn];
    param.epc = [self.epcSwitch isOn];
    param.tid = [self.tidSwitch isOn];
    param.user = [self.userSwitch isOn];
    
    int time = [self.operationTimeTextField.text intValue];
    
    [appDelegate.mReader setOperationTime:time];
    [systemSetting setOperationTime:time];
    if ([appDelegate.mReader unlock:param] != ResultNoError) {
    };
}

- (IBAction)permalockBtnTapped:(id)sender {
    isActionResult = NO;
    
    [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
    
    LockParam *param = [[LockParam alloc] init];
    param.killPassword = [self.killPasswordSwitch isOn];
    param.accessPassword = [self.accessPasswordSwitch isOn];
    param.epc = [self.epcSwitch isOn];
    param.tid = [self.tidSwitch isOn];
    param.user = [self.userSwitch isOn];
    
    int time = [self.operationTimeTextField.text intValue];
    
    [appDelegate.mReader setOperationTime:time];
    [systemSetting setOperationTime:time];

    if ([appDelegate.mReader permaLock:param] != ResultNoError) {
    };
}

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

- (IBAction)setAccessPwdBtnTapped:(id)sender {
    isActionResult = NO;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Set Access Password:" message:@"Please enter password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
    [alert textFieldAtIndex:0].delegate = self;
    alert.tag = ALERT_VIEW_SET_ACCESS_PW;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)setKillPwdBtnTapped:(id)sender {
    isActionResult = NO;
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Set Kill Password:" message:@"Please enter password." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
    [alert textFieldAtIndex:0].delegate = self;
    alert.tag = ALERT_VIEW_SET_KILL_PW;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}
- (IBAction)clearBtnTapped:(id)sender {
    self.selectionTagLabel.text = @"Result";
    self.messageLabel.text = MSG_TAG_WAIT;
    self.rssiLabel.text = @"0.0 dB";
    self.phaseLabel.text = @"0.0˚";
}
- (IBAction)maskBtnTapped:(id)sender {
    if (maskType == MaskType_Selection) {
        [self performSegueWithIdentifier:@"SelectionMask" sender:self];
    } else  {
        currentAlertView = [[UIAlertView alloc] initWithTitle:@"" message:@"Please choosing the Selection Mask type in the RFID Option menu." delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        return;
    }
}

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

- (IBAction)powerGainPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    idx += (appDelegate.mReader.powerGainRange.min / 10);
    [self setPowerGain:idx];
    appDelegate.mReader.powerGain = (int)idx * 10;
    [systemSetting setPowerGain:(int)idx * 10];
    [self hidePickerView];
}


#pragma mark - Custom
- (void) hidePickerView {
    self.powerGainPickerTopView.hidden = YES;
    self.pickerView.hidden = YES;
}

- (void)setPassword:(NSString *)password {
    self.passwordTextField.text = password;
}

- (void)setPowerGain:(NSInteger)power {
    NSString *value = [NSString stringWithFormat:@"%i.0 dB", power];
    NSInteger index = [self.powerGainPickerData indexOfObject:value];
    if ([self.powerGainPickerData count] >index) {
        self.powerGainTextField.text = [self.powerGainPickerData objectAtIndex:index];
    }
}

- (void)setOperationTime:(NSString *)operationTime {
    self.operationTimeTextField.text = operationTime;
}

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

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

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

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

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


#pragma mark - Reader Event Handler Methods
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
//    [appDelegate.mReader setSacnModel:RFIDScanModel];
    if (status) {
        [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];
        currentAlertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"For this page no Trigger key function." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
    }
    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) {
        
#ifdef DEBUG
#else
        [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];
        currentAlertView = [[UIAlertView alloc]initWithTitle:@"Error" message:@"Failed to get response. Try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        [self.navigationController popViewControllerAnimated:YES];
#endif
    }
}
- (void)changedActionState:(CommandType)action resultCode:(NSInteger)resultCode {
    [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];

    if (action == CommandStop) {
        if (isActionResult == NO)
            self.messageLabel.text = MSG_TAG_WAIT;
    } else {
        
        currentAlertView = [[UIAlertView alloc] initWithTitle:@"On progress" message:@"Waiting Tag Memory" delegate:self cancelButtonTitle:@"Stop" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_LOCK;
        [currentAlertView show];
    }
}
- (void)readTag:(NSString *)tag rssi:(float)rssi phase:(float)phase {
}

- (void)accessResult:(ResultCode)error actionState:(CommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase frequency:(float)frequency{
    NSLog(@"ResultCode = %02x %02x %@ %@ %f %f ",error,action,epc,data,rssi,phase);
    isActionResult = YES;
    [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];

    self.selectionTagLabel.text = epc;
    
    if (error != ResultNoError) {
        self.messageLabel.text = [AsResultCode msg:error];
        currentAlertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[AsResultCode msg:error] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
        [currentAlertView show];
        return;
    }
    
    self.messageLabel.text = @"Success";
    
    if (![self.reportRssiSwitch isOn]) {
        [self setReportRssiModeDefault];
    } else {
        self.rssiLabel.text = [NSString stringWithFormat:@"%.1f dB", rssi];
        self.phaseLabel.text = [NSString stringWithFormat:@"%.1f˚", phase];
    }
    
//    currentAlertView = [[UIAlertView alloc] initWithTitle:@"Success" message:@"Write memory successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//    currentAlertView.tag = ALERT_VIEW_OUTHERVIEW;
//    [currentAlertView show];
}
@end
