//
//  ReadViewController.m
//  ASR033W
//
//  Created by mac on 2020/12/9.
//

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

@interface ReadViewController ()<ASR033WDelegate, UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UIScrollView *backScroView;
@property (strong, nonatomic) IBOutlet UITextField *matchTextField;
@property (strong, nonatomic) IBOutlet UISegmentedControl *readSegment;
@property (strong, nonatomic) IBOutlet UITextView *readTextView;
@property (strong, nonatomic) IBOutlet UITextField *epcOffsetTextField;
@property (strong, nonatomic) IBOutlet UITextField *epcLenghtTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@end

@implementation ReadViewController
{
    ASR033W *asr033w;
    ASR033WMemoryBank memoryBankType;
    System *system;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.matchTextField.text = _epcData.epc;
    self.backScroView.contentSize = CGSizeMake(0, self.epcLenghtTextField.frame.origin.y + self.epcLenghtTextField.frame.size.height + 100);
    self.readTextView.layer.masksToBounds = YES;
    self.readTextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.readTextView.layer.borderWidth = 1;
    self.readTextView.layer.cornerRadius = 5;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewBack)];
    [self.backScroView addGestureRecognizer:tap];
    system = [System sharedSystem];
    asr033w = [ASR033W sharedInstance];
    memoryBankType = ASR033WMemoryBank_Reserved;
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    asr033w.delegate = self;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    asr033w.delegate = nil;
}
#pragma mark - Action
- (IBAction)onClickDoneBarItem:(UIBarButtonItem *)sender {
    [self.view endEditing:YES];
    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];
    self.readTextView.text = @"";
    NSData *epcs = [self.matchTextField.text hexStringToBytes];
    NSData *pcs = [_epcData.pc hexStringToBytes];
    int a = [Utils getDecimal:self.passwordTextField.text];
    [asr033w readMemory:memoryBankType offset:[self.epcOffsetTextField.text intValue] length:[self.epcLenghtTextField.text intValue] epc:epcs pc:pcs 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]];
}
- (IBAction)onClickReadSegment:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
        {
            memoryBankType = ASR033WMemoryBank_Reserved;
            self.epcOffsetTextField.enabled = YES;
            self.epcOffsetTextField.text = @"0";
            self.epcLenghtTextField.text = @"0";
        }
            break;
        case 1:
        {
            memoryBankType = ASR033WMemoryBank_EPC;
            self.epcOffsetTextField.enabled = YES;
            self.epcOffsetTextField.text = @"2";
            self.epcLenghtTextField.text = @"0";
        }
            break;
        case 2:
        {
            memoryBankType =ASR033WMemoryBank_TID;
            self.epcOffsetTextField.enabled = NO;
            self.epcOffsetTextField.text = @"0";
            self.epcLenghtTextField.text = @"6";
        }
            break;
        case 3:
        {
            memoryBankType = ASR033WMemoryBank_User;
            self.epcOffsetTextField.enabled = YES;
            self.epcOffsetTextField.text = @"0";
            self.epcLenghtTextField.text = @"0";
        }
            break;
        default:
            break;
    }
}
#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 {
    
}
- (void)accessASR033WResult:(ASR033WResultCode)error actionState:(ASR033WCommandType)action epc:(NSString *)epc data:(NSString *)data rssi:(float)rssi phase:(float)phase frequency:(float)frequency {
    NSLog (@"error = %u, action = %u, epc = %@, data = %@, RSSI = %f, phase = %f, frequency = %f", error, action, epc, data, rssi, phase, frequency);
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(dismissHUD) object:nil];
        [SVProgressHUD dismiss];
        if (action == ASR033WCommandReadMemory) {
            if (error == ASR033WResultNoError) {
                [Utils showAlert:@"" message:@"Success"];
                self.readTextView.text = data;
            } else {
                [Utils showAlert:@"Error" message:[self->asr033w getMessageWithASR033WResultCode:error]];
            }
        } else {
            [Utils showAlert:@"Error" message:[self->asr033w getMessageWithASR033WResultCode:ASR033WResultOtherError]];
        }
    }];
}
#pragma mark - Private
- (void)viewBack {
    [self.backScroView endEditing:YES];
}
- (void)dismissHUD {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [self->asr033w stopInventory];
        [SVProgressHUD dismiss];
    }];
}
@end
