//
//  LockViewController.m
//  ASR033W
//
//  Created by mac on 2020/12/11.
//

#import "LockViewController.h"
#import <ASR033WSDK/ASR033WSDK.h>
#import <SVProgressHUD/SVProgressHUD.h>
#import "Utils.h"
#import "System.h"

@interface LockViewController ()<ASR033WDelegate, UIPickerViewDelegate, UIPickerViewDataSource, UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *matchTextField;
@property (strong, nonatomic) IBOutlet UILabel *lockLabel;
@property (strong, nonatomic) IBOutlet UILabel *operationLabel;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UIBarButtonItem *lockBarItem;
@property (strong, nonatomic) UIPickerView *lockPickerView;
@property (strong, nonatomic) UIPickerView *operatioPickerView;
@end

@implementation LockViewController
{
    ASR033W *asr033w;
    NSArray *lockArray;
    NSArray *operationArray;
    BOOL lockStatus;
    BOOL operationStatus;
    ASR033WLockBank lockBank;
    ASR033WLockType lockType;
    System *system;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.matchTextField.text = _epcData.epc;
    system = [System sharedSystem];
    asr033w = [ASR033W sharedInstance];
    lockBank = ASR033WLockBank_Kill;
    lockType = ASR033WLockType_Unlock;
    lockStatus = NO;
    operationStatus = NO;
    self.lockLabel.layer.masksToBounds = YES;
    self.lockLabel.layer.borderColor = [[UIColor colorWithRed:229 / 255.f green:229 / 255.f blue:234 / 255.f alpha:1] CGColor];
    self.lockLabel.layer.borderWidth = 1;
    self.lockLabel.layer.cornerRadius = 5;

    self.operationLabel.layer.masksToBounds = YES;
    self.operationLabel.layer.borderColor = [[UIColor colorWithRed:229 / 255.f green:229 / 255.f blue:234 / 255.f alpha:1] CGColor];
    self.operationLabel.layer.borderWidth = 1;
    self.operationLabel.layer.cornerRadius = 5;

    self.lockLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *lockLabelTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(lock)];
    [self.lockLabel addGestureRecognizer:lockLabelTap];

    self.operationLabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *operationTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(operation)];
    [self.operationLabel addGestureRecognizer:operationTap];
    
    lockArray = [NSArray arrayWithObjects: @"Kill password",
                                           @"Access password",
                                           @"EPC",
                                           @"TID",
                                           @"Userdata", nil];
    
    operationArray = [NSArray arrayWithObjects: @"Unlock",
                                                @"Lock",
                                                @"PermaUnlock",
                                                @"PermaLock", nil];
    self.lockPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 200 - 64, [UIScreen mainScreen].bounds.size.width, 200)];
    self.lockPickerView.delegate = self;
    self.lockPickerView.dataSource = self;
    self.lockPickerView.hidden = YES;
    self.lockPickerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.lockPickerView];
    [self.lockPickerView selectRow:lockBank inComponent:0 animated:NO];

    self.operatioPickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, [UIScreen mainScreen].bounds.size.height - 200 - 64, [UIScreen mainScreen].bounds.size.width, 200)];
    self.operatioPickerView.delegate = self;
    self.operatioPickerView.dataSource = self;
    self.operatioPickerView.hidden = YES;
    self.operatioPickerView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.operatioPickerView];
    [self.operatioPickerView selectRow:lockType inComponent:0 animated:NO];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    asr033w.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    asr033w.delegate = nil;
}
#pragma mark - Action
- (IBAction)onClickLockBarItem:(UIBarButtonItem *)sender {
    [self.view endEditing:YES];
    if ([self.passwordTextField.text isEqualToString:@""]) {
        [Utils showAlert:@"Error" message:@"Please enter your password"];
        return;
    }
    NSString *password = @"00000000";
    if (self.passwordTextField.text.length > 0) {
        if (self.passwordTextField.text.length != 8) {
            [Utils showAlert:@"Error" message:@"Please enter your eight-digit password"];
            return;
        } else {
            password = self.passwordTextField.text;
        }
    }
    [self performSelector:@selector(dismissHUD) withObject:nil afterDelay:10];
    [SVProgressHUD show];
    NSData *epcs = [self.matchTextField.text hexStringToBytes];
    [asr033w lockMemory:lockBank lockType:lockType epc:epcs password:[Utils getDecimal:password] antenna1:[system getAnt1Status] antenna2:[system getAnt2Status] antenna3:[system getAnt3Status] antenna4:[system getAnt4Status] antenna5:[system getAnt5Status] antenna6:[system getAnt6Status] antenna7:[system getAnt7Status] antenna8:[system getAnt8Status]];
}
#pragma mark - UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 1;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (pickerView == self.lockPickerView) {
        return lockArray.count;
    } else {
        return operationArray.count;
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component{
    if (pickerView == self.lockPickerView) {
        return [lockArray objectAtIndex:row];
    } else {
        return [operationArray objectAtIndex:row];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component{
    if (pickerView == self.lockPickerView) {
        [self lock];
        lockBank = (ASR033WLockBank)row;
        self.lockLabel.text = [lockArray objectAtIndex:row];
    } else {
        [self operation];
        lockType = (ASR033WLockType)row;
        self.operationLabel.text = [operationArray objectAtIndex:row];
        if (lockType == ASR033WLockType_Lock || lockType == ASR033WLockType_PermaLock) {
            [self.lockBarItem setTitle:@"Lock"];
        } else {
            [self.lockBarItem setTitle:@"Unlock"];
        }
    }
}
#pragma mark - UITextField delegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.passwordTextField) {
        if ([Utils isCorrectWriteData:[textField.text stringByAppendingString:string]]) {
            return YES;
        } else {
            return NO;
        }
    }
    return YES;
}
#pragma mark - ASR033WDelegate
- (void)receivedASR033WNetworkState:(ASR033WNetworkState)state error:(NSError *)error {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (state != ASR033WNetworkStateConnected) {
            [self.navigationController popToRootViewControllerAnimated:YES];
        }
    }];
}
- (void)receivedASR033WDeviceState:(ASR033WResultCode)error {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if (error != ASR033WResultNoError) {
            [Utils showAlert:@"Error" message:@"Failed to get response. Try again."];
        }
    }];
}
- (void)receivedASR033WActionState:(ASR033WCommandType)action resultCode:(ASR033WResultCode)resultCode {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismissHUD) object:nil];
        [SVProgressHUD dismiss];
        if (action == ASR033WCommandLock) {
            if (resultCode == ASR033WResultNoError) {
                [Utils showAlert:@"" message:@"Success"];
            } else {
                [Utils showAlert:@"Error" message:[self->asr033w getMessageWithASR033WResultCode:resultCode]];
            }
        } else {
            [Utils showAlert:@"Error" message:[self->asr033w getMessageWithASR033WResultCode:ASR033WResultOtherError]];
        }
    }];
}
- (void)accessASR033WResult:(ASR033WResultCode)error actionState:(ASR033WCommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase frequency:(float)frequency {
    
}
#pragma mark - System
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark - Private
- (void)viewBack {
    [self.view endEditing:YES];
}
- (void)dismissHUD {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [SVProgressHUD dismiss];
    }];
}
- (void)lock {
    if (lockStatus) {
        lockStatus = NO;
        self.lockPickerView.hidden = YES;
    } else {
        lockStatus = YES;
        self.lockPickerView.hidden = NO;
    }
}
- (void)operation {
    if (operationStatus) {
        operationStatus = NO;
        self.operatioPickerView.hidden = YES;
    } else {
        operationStatus = YES;
        self.operatioPickerView.hidden = NO;
    }
}
@end
