#define PICKER_VIEW_TARGET  0
#define PICKER_VIEW_ACTION  1
#define PICKER_VIEW_BANK    2
#define PICKER_VIEW_OFFSET  3
#define PICKER_VIEW_LENGTH  4

#define ALERT_VIEW_MASK     0

#import "SelectionMaskEditViewController.h"
#import "AppDelegate.h"

@interface SelectionMaskEditViewController ()<AsReaderDelegate>

@property (weak, nonatomic) IBOutlet UITextField *targetTextField;
@property (weak, nonatomic) IBOutlet UITextField *actionTextField;
@property (weak, nonatomic) IBOutlet UITextField *bankTextField;
@property (weak, nonatomic) IBOutlet UITextField *offsetTextField;
@property (weak, nonatomic) IBOutlet UITextField *maskTextField;
@property (weak, nonatomic) IBOutlet UITextField *lengthTextField;
@property (strong, nonatomic) NSArray *targetPickerData;
@property (strong, nonatomic) NSArray *actionPickerData;
@property (strong, nonatomic) NSArray *bankPickerData;
@property (strong, nonatomic) NSArray *offsetPickerData;
@property (strong, nonatomic) NSArray *lengthPickerData;
@property (strong, nonatomic) NSArray *bitData;
@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UIView *targetPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *actionPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *bankPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *offsetPickerTopView;
@property (weak, nonatomic) IBOutlet UIView *lengthPickerTopView;

@end

@implementation SelectionMaskEditViewController{
    AppDelegate *appDelegate;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    if (_selectMaskParam != nil) {
        [self setTarget:self.selectMaskParam.target];
        [self setAction:self.selectMaskParam.action];
        [self setBank:self.selectMaskParam.bank];
        [self setOffset:[self getBitDataIndex:self.selectMaskParam.offset]];
        [self setMask:self.selectMaskParam.mask];
        [self setLength:[self getBitDataIndex:self.selectMaskParam.length]];
    } else {
        [self setTarget:MaskTarget_SL];
        [self setAction:MaskAction_AB];
        [self setBank:Bank_EPC];
        [self setOffset:1];
        [self setLength:1];
    }
}
- (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)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNDisconnected" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"AsReaderGUNConnected" object:nil];
    [appDelegate.mReader setDelegate:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


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

- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)identifier sender:(id)sender {
    if ([identifier isEqualToString:@"BackToSource"]) {
        NSInteger maskBit = [[self.bitData objectAtIndex:[self.lengthPickerData indexOfObject:self.lengthTextField.text]] integerValue];
        
        if ([self.maskTextField.text length] != maskBit / 4) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Mask length is not valid" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [alert show];
            return NO;
        }
    }
    return YES;
}

#pragma mark - UIPickerViewDelegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_TARGET) {
        return self.targetPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_ACTION) {
        return self.actionPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_BANK) {
        return self.bankPickerData.count;
    } else if (pickerView.tag == PICKER_VIEW_OFFSET) {
        return self.bitData.count;
    } else if (pickerView.tag == PICKER_VIEW_LENGTH) {
        return self.lengthPickerData.count;
    }
    return 0;
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (pickerView.tag == PICKER_VIEW_TARGET) {
        return [self.targetPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_ACTION) {
        return [self.actionPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_BANK) {
        return [self.bankPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_OFFSET) {
        return [self.offsetPickerData objectAtIndex:row];
    } else if (pickerView.tag == PICKER_VIEW_LENGTH) {
        return [self.lengthPickerData objectAtIndex:row];
    }
    return @"None";
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == ALERT_VIEW_MASK) {
        if (buttonIndex == 1) {
            NSString * value = [alertView textFieldAtIndex:0].text;
            [self setMask:value];
        } else {
            [self setMask:@""];
        }
    }
}

#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    NSCharacterSet* nonHex = [[NSCharacterSet
                               characterSetWithCharactersInString: @"0123456789ABCDEFabcdef"]
                              invertedSet];
    NSRange nonHexRange = [string rangeOfCharacterFromSet:nonHex];
    BOOL isHex = (nonHexRange.location == NSNotFound);
    
    if (isHex) {
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
        textField.text = [newString uppercaseString];
    }
    return NO;
}
#pragma mark - Getters
-(NSArray *)targetPickerData {
    if (_targetPickerData == nil) {
        _targetPickerData = DATA_TARGET;
    }
    return _targetPickerData;
}

-(NSArray *)actionPickerData {
    if (_actionPickerData == nil) {
        _actionPickerData = DATA_ACTION;
    }
    return _actionPickerData;
}

- (NSArray *)bankPickerData {
    if (_bankPickerData == nil) {
        _bankPickerData = DATA_BANK;
    }
    return _bankPickerData;
}

- (NSArray *)offsetPickerData {
    if (_offsetPickerData == nil) {
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        for (NSString *offset in self.bitData) {
            [tmpArray addObject:[NSString stringWithFormat:@"%@ bit", offset]];
        }
        _offsetPickerData = tmpArray;
    }
    return _offsetPickerData;
}
- (NSArray *)lengthPickerData {
    if (_lengthPickerData == nil) {
        NSMutableArray *tmpArray = [[NSMutableArray alloc] init];
        for (NSString *offset in self.bitData) {
            [tmpArray addObject:[NSString stringWithFormat:@"%@ bit", offset]];
        }
        _lengthPickerData = tmpArray;
    }
    return _lengthPickerData;
}

- (NSArray *)bitData {
    if (_bitData == nil) {
        _bitData = DATA_BIT;
    }
    return _bitData;
}

- (AsSelectMaskParam *)selectMaskParam {
    if (_selectMaskParam == nil) {
        _selectMaskParam = [[AsSelectMaskParam alloc] init];
    }
    return _selectMaskParam;
}
#pragma mark - IBAction
- (IBAction)targetBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_TARGET;
    [self.pickerView reloadAllComponents];
    
    if (![self.targetTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.targetPickerData indexOfObject:self.targetTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.targetPickerTopView.hidden = NO;
}

- (IBAction)actionBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_ACTION;
    [self.pickerView reloadAllComponents];
    
    if (![self.actionTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.actionPickerData indexOfObject:self.actionTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.actionPickerTopView.hidden = NO;
}

- (IBAction)bankBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_BANK;
    [self.pickerView reloadAllComponents];
    
    if (![self.bankTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.bankPickerData indexOfObject:self.bankTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.bankPickerTopView.hidden = NO;
}

- (IBAction)offsetBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_OFFSET;
    [self.pickerView reloadAllComponents];
    
    if (![self.offsetTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.offsetPickerData indexOfObject:self.offsetTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.offsetPickerTopView.hidden = NO;
}

- (IBAction)maskBtnTapped:(id)sender {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mask:" message:@"Please enter mask value." delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:nil];
    
    alert.alertViewStyle = UIAlertViewStylePlainTextInput;
    [alert textFieldAtIndex:0].keyboardType = UIKeyboardTypeAlphabet;
    [alert textFieldAtIndex:0].delegate = self;
    [alert textFieldAtIndex:0].text = self.maskTextField.text;
    alert.tag = ALERT_VIEW_MASK;
    
    [alert addButtonWithTitle:@"OK"];
    [alert show];
}

- (IBAction)lengthBtnTapped:(id)sender {
    self.pickerView.tag = PICKER_VIEW_LENGTH;
    [self.pickerView reloadAllComponents];
    
    if (![self.lengthTextField.text isEqualToString:@""]) {
        [self.pickerView selectRow:[self.lengthPickerData indexOfObject:self.lengthTextField.text] inComponent:0 animated:NO];
    } else {
        [self.pickerView selectRow:0 inComponent:0 animated:NO];
    }
    
    self.pickerView.hidden = NO;
    self.lengthPickerTopView.hidden = NO;
}

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

- (IBAction)targetPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setTarget:idx];
    [self hidePickerView];
}

- (IBAction)actionPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setAction:idx];
    [self hidePickerView];
}
- (IBAction)bankPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setBank:idx];
    [self hidePickerView];
}
- (IBAction)offsetPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setOffset:idx];
    [self hidePickerView];
}

- (IBAction)lengthPickerOkBtnTapped:(id)sender {
    NSInteger idx = [self.pickerView selectedRowInComponent:0];
    [self setLength:idx];
    [self hidePickerView];
}

#pragma mark - Custom
- (void) hidePickerView {
    self.targetPickerTopView.hidden = YES;
    self.actionPickerTopView.hidden = YES;
    self.bankPickerTopView.hidden = YES;
    self.offsetPickerTopView.hidden = YES;
    self.lengthPickerTopView.hidden = YES;
    self.pickerView.hidden = YES;
}

- (void)setTarget:(NSInteger)index {
    self.targetTextField.text = [self.targetPickerData objectAtIndex:index];
    self.selectMaskParam.target = (int)index;
}
- (void)setAction:(NSInteger)index {
    self.actionTextField.text = [self.actionPickerData objectAtIndex:index];
    self.selectMaskParam.action = (int)index;
}
- (void)setBank:(NSInteger)index {
    self.bankTextField.text = [self.bankPickerData objectAtIndex:index];
    self.selectMaskParam.bank = (int)index;
}
- (void)setOffset:(NSInteger)index {
    self.offsetTextField.text = [self.offsetPickerData objectAtIndex:index];
    self.selectMaskParam.offset = [[self.bitData objectAtIndex:index] intValue];
}
- (void)setMask:(NSString *)mask {
    self.maskTextField.text = mask;
    self.selectMaskParam.mask = mask;
}
- (void)setLength:(NSInteger)index {
    self.lengthTextField.text = [self.lengthPickerData objectAtIndex:index];
    self.selectMaskParam.length = [[self.bitData objectAtIndex:index] intValue];
}

- (NSInteger)getBitDataIndex:(NSInteger)bit {
    return [self.bitData indexOfObject:[NSString stringWithFormat:@"%ld", (long)bit]];
}
- (BOOL)onAsReaderTriggerKeyEvent:(BOOL)status{
    return NO;
}

#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];
    });
}
@end
