//
//  LockMemoryViewController.m
//  AT288N_DEMO
//
//  Created by 류은주 on 2017. 8. 7..
//  Copyright © 2017년 ATID. All rights reserved.
//
#define ALERT_VIEW_LOCK             5

#define MSG_TAG_WAIT        @"Tag memory to lock, Please click the button"


#import "LockMemoryViewController.h"
#import "SWRevealViewController.h"

@interface LockMemoryViewController ()
{
    AppDelegate *appDelegate;
    BOOL isActionResult;
    UIAlertView *currentAlertView;
    
    int opmode;
    
    int setItem;
    
    bool isprocess;
    
}

@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property (weak, nonatomic) IBOutlet UILabel *messageLabel;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UIButton *killpasswordBtn;
@property (weak, nonatomic) IBOutlet UITextField *killPasswordTextField;
@property (weak, nonatomic) IBOutlet UITextField *accessPasswordTextField;
@property (weak, nonatomic) IBOutlet UITextField *epcTextField;
@property (weak, nonatomic) IBOutlet UITextField *tidTextField;
@property (weak, nonatomic) IBOutlet UITextField *userTextField;
@property (weak, nonatomic) IBOutlet UIButton *accesspasswordBtn;
@property (weak, nonatomic) IBOutlet UIBarButtonItem *menuopen;
@property (weak, nonatomic) IBOutlet UIPickerView *accessPickerView;
@property (weak, nonatomic) IBOutlet UIView *pickerTopView;
@property (weak, nonatomic) IBOutlet UIView *shadowView;
@property (strong, nonatomic) NSArray *accesslist;
@end

@implementation LockMemoryViewController

- (void)viewDidLoad {
    [super viewDidLoad];
        SWRevealViewController *revealController = self.revealViewController;
        if(revealController)
        {
            [self.menuopen setTarget:self.revealViewController];
            [self.menuopen setAction:@selector(revealToggle:)];
            [self.view addGestureRecognizer:self.revealViewController.panGestureRecognizer];
        }
    
    
    
//    [AppDelegate showGlobalProgressHUDWithTitle:@"Loading..."];
    HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
    HUD.labelText = @"Loading...";
    [self.navigationController.view addSubview:HUD];
    [HUD show:YES];
    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        // Do something...
        appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
        [appDelegate.mReader setDelegate:self];
        
        if (appDelegate.mReader == nil) {
            return;
        }
        
        opmode = 0;
        
        isActionResult = NO;
        
        dispatch_async(dispatch_get_main_queue(), ^{
        
            [AppDelegate dismissGlobalHUD];
            [HUD hide:YES];
            [HUD removeFromSuperview];
        });
    });
    
}
-(void) viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(BluetoothDisconnected) name:@"BluetoothDisconnected" object:nil];
    
    [appDelegate.mReader setDelegate:self];
    
    _accesslist = @[@"Not Changed",@"Lock", @"Unlock",@"Permalock"];
    
    dispatch_async(dispatch_get_main_queue(), ^{
        self.killPasswordTextField.text = [_accesslist objectAtIndex:appDelegate.killpasswordvalue];
        self.accessPasswordTextField.text = [_accesslist objectAtIndex:appDelegate.accesspasswordvalue];
        self.epcTextField.text = [_accesslist objectAtIndex:appDelegate.epcvalue];
        self.tidTextField.text = [_accesslist objectAtIndex:appDelegate.tidvalue];
        self.userTextField.text = [_accesslist objectAtIndex:appDelegate.uservalue];
    });
    
}
-(void) viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    
    isprocess = 0;
}
-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BluetoothDisconnected" object:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(IBAction)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    
}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == ALERT_VIEW_LOCK) {
         [appDelegate.mReader stop];
        isprocess = 0;
    }
}
#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 - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
  
    return _accesslist.count;
    
}

#pragma mark - UIPickerViewDelegate
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
 
    return [_accesslist objectAtIndex:row];
    
}

- (void) showpickerviewset {
    self.shadowView.hidden = NO;
    self.pickerTopView.hidden = NO;
    self.accessPickerView.hidden = NO;
}

- (void) hidepickerviewset {
    self.shadowView.hidden = YES;
    self.pickerTopView.hidden = YES;
    self.accessPickerView.hidden = YES;
}
- (IBAction)cancleTapped:(id)sender {
    [self hidepickerviewset];
}
- (IBAction)confirmTapped:(id)sender {
    NSInteger idx = [self.accessPickerView selectedRowInComponent:0];
    if(setItem == 0){
        appDelegate.killpasswordvalue = (int)idx;
        self.killPasswordTextField.text = [_accesslist objectAtIndex:appDelegate.killpasswordvalue];
    } else if(setItem == 1){
        appDelegate.accesspasswordvalue = (int)idx;
        self.accessPasswordTextField.text = [_accesslist objectAtIndex:appDelegate.accesspasswordvalue];
    } else if(setItem == 2){
        appDelegate.epcvalue = (int)idx;
        self.epcTextField.text = [_accesslist objectAtIndex:appDelegate.epcvalue];
    } else if(setItem == 3){
        appDelegate.tidvalue = (int)idx;
        self.tidTextField.text = [_accesslist objectAtIndex:appDelegate.tidvalue];
    } else if(setItem == 4){
        appDelegate.uservalue = (int)idx;
        self.userTextField.text = [_accesslist objectAtIndex:appDelegate.uservalue];
    }
        
    [self hidepickerviewset];
}
- (IBAction)killpasswordTapped:(id)sender {
    setItem = 0;
    [self.accessPickerView reloadAllComponents];
    [self.accessPickerView selectRow:appDelegate.killpasswordvalue inComponent:0 animated:NO];
    [self showpickerviewset];
}
- (IBAction)accesspasswordTapped:(id)sender {
    setItem = 1;
    [self.accessPickerView selectRow:appDelegate.accesspasswordvalue inComponent:0 animated:NO];
    [self showpickerviewset];
}
- (IBAction)epcTapped:(id)sender {
    setItem = 2;
    [self.accessPickerView selectRow:appDelegate.epcvalue inComponent:0 animated:NO];
    [self showpickerviewset];
}
- (IBAction)tidTapped:(id)sender {
    setItem = 3;
    [self.accessPickerView selectRow:appDelegate.tidvalue inComponent:0 animated:NO];
    [self showpickerviewset];
}
- (IBAction)userTapped:(id)sender {
    setItem = 4;
    [self.accessPickerView selectRow:appDelegate.uservalue inComponent:0 animated:NO];
    [self showpickerviewset];
}

- (IBAction)startBtnTapped:(id)sender {
    
    if(isprocess){
        return;
    }
    isprocess = 1;
    LockParam *param = [[LockParam alloc] init];
    param.killPassword = appDelegate.killpasswordvalue;
    param.accessPassword = appDelegate.accesspasswordvalue;
    param.epc = appDelegate.epcvalue;
    param.tid = appDelegate.tidvalue;
    param.user = appDelegate.uservalue;
    
    [appDelegate.mReader setAccessPassword:self.passwordTextField.text];
    
    if([appDelegate.mReader lock:param tagmask:appDelegate.maskstrvalue] != ResultNoError){
        NSLog(@"ERROR. Failed to start lock tag");
    }
}

- (IBAction)passwordBtnTapped:(id)sender {
    isActionResult = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Password:" message:@"Please enter  password." preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.keyboardType = UIKeyboardTypeAlphabet;
        textField.text = self.passwordTextField.text;
        textField.delegate = self;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action) {
                             UITextField* textField = alert.textFields.firstObject;
                             [self setPassword:textField.text];
                             
                             [alert dismissViewControllerAnimated:YES completion:nil];
                         }];
    
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action)
                             {
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                             }];
    
    [alert addAction:cancel];
    [alert addAction:ok];
    
    [self presentViewController:alert animated:YES completion:nil];
    
}

- (IBAction)clearBtnTapped:(id)sender {
    self.resultLabel.text = @"Result";
    self.messageLabel.text = MSG_TAG_WAIT;
}
- (IBAction)setPasswordBtnTapped:(id)sender {
    
    isActionResult = NO;
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Set Access Password:" message:@"Please enter Password." preferredStyle:UIAlertControllerStyleAlert];
    
    [alert addTextFieldWithConfigurationHandler:^(UITextField *textField){
        textField.keyboardType = UIKeyboardTypeAlphabet;
        textField.text = self.passwordTextField.text;
        textField.delegate = self;
    }];
    
    UIAlertAction* ok = [UIAlertAction
                         actionWithTitle:@"OK"
                         style:UIAlertActionStyleDefault
                         handler:^(UIAlertAction * action){
                             UITextField* textField = alert.textFields.firstObject;
                        
                             [alert dismissViewControllerAnimated:YES completion:nil];
                        }];
    UIAlertAction* cancel = [UIAlertAction
                             actionWithTitle:@"Cancel"
                             style:UIAlertActionStyleDefault
                             handler:^(UIAlertAction * action){
                                 [alert dismissViewControllerAnimated:YES completion:nil];
                            }];
    [alert addAction:ok];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
-(void) setPassword:(NSString *)password {
    self.passwordTextField.text = password;
    [appDelegate.mReader setAccessPassword:password];
}
#pragma mark - Reader Event Handler Methods
-(void)deviceStateChange:(ResultType)error {
    if(error != ResultNoError) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error" message:@"Failed to get response. Try again." 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];
    }
}
-(void)changedActionState:(CommandType)action {
    if (action == CommandStop) {
        //        [currentAlertView dismissViewControllerAnimated:YES completion:nil];
        [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];
        
        if(isActionResult == NO){
            self.messageLabel.text = MSG_TAG_WAIT;
        }
        isprocess = 0;
        
    } 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)readTagResult:(NSString *)tag extradata:(NSString *)extradata {
    
    NSLog(@"LOCK Memory readTagResult tag %@",tag);

}
- (void) memoryaccessresult:(int)result {
    isActionResult = YES;
    [appDelegate.mReader stop];
    [currentAlertView dismissWithClickedButtonIndex:0 animated:NO];
    if(result == 0){
        self.messageLabel.text = @"Fail";
    }else if(result == 1){
        self.messageLabel.text = @"Success";
    }else if(result == 2){
        self.messageLabel.text = @"Undefined Error";
    }else if(result == 3){
        self.messageLabel.text = @"Memory Overrun";
    }else if(result == 4){
        self.messageLabel.text = @"Memory Locked";
    }else if(result == 5){
        self.messageLabel.text = @"Insufficient Power";
    }else if(result == 6){
        self.messageLabel.text = @"Non-Specific Error";
    }else {
       self.messageLabel.text = @"TimeOut";
    }

    isprocess = 0;
}

-(void) BluetoothDisconnected {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"BarcodeViewController BluetoohDisconnected");
        [self performSegueWithIdentifier:@"RegistDevice" sender:nil];
    });
}

@end
