//
//  WriteViewController.m
//  ASR033W
//
//  Created by mac on 2020/12/4.
//

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

@interface WriteViewController ()<ASR033WDelegate, UITextViewDelegate, UITextFieldDelegate>
@property (strong, nonatomic) IBOutlet UITextField *currentDataTextField;
@property (strong, nonatomic) IBOutlet UISegmentedControl *currentTypeSegment;
@property (strong, nonatomic) IBOutlet UITextView *writeTextView;
@property (strong, nonatomic) IBOutlet UITextField *startWriteAddressTextField;
@property (strong, nonatomic) IBOutlet UITextField *lenghtTextField;
@property (strong, nonatomic) IBOutlet UITextField *passwordTextField;
@property (strong, nonatomic) IBOutlet UISwitch *cwSwitch;
@end

@implementation WriteViewController
{
    ASR033W *asr033w;
    System *system;
    ASR033WMemoryBank memoryBankType;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    system = [System sharedSystem];
    asr033w = [ASR033W sharedInstance];
    self.writeTextView.layer.masksToBounds = YES;
    self.writeTextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.writeTextView.layer.borderWidth = 1;
    self.writeTextView.layer.cornerRadius = 5;
    self.currentDataTextField.text = _epcData.epc;
    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 - 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 == ASR033WCommandWriteMemory) {
            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 - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView {
    NSString *string = textView.text;
    if ((int)string.length % 4 > 0) {
        self.lenghtTextField.text = [NSString stringWithFormat:@"%d", (int)string.length / 4 + 1];
    } else {
        self.lenghtTextField.text = [NSString stringWithFormat:@"%d", (int)string.length / 4];
    }
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if (textView == self.writeTextView) {
        if ([Utils isCorrectWriteData:[textView.text stringByAppendingString:text]]) {
            return YES;
        } else {
            return NO;
        }
    }
    return YES;
}
#pragma mark - Action
- (IBAction)onClickDoneBarItem:(UIBarButtonItem *)sender {
    [self.view endEditing:YES];
    if ([self.writeTextView.text isEqualToString:@""] && [self.startWriteAddressTextField.text isEqualToString:@""]) {
        [Utils showAlert:@"Error" message:@"Please enter write value"];
        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.currentDataTextField.text hexStringToBytes];
    NSData *data = [self.writeTextView.text hexStringToBytes];
    [asr033w writeMemory:memoryBankType offset:[self.startWriteAddressTextField.text intValue] length:[self.lenghtTextField.text intValue] writeData:data epc:epcs cw:self.cwSwitch.on 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)onClickWritedTypeSegment:(UISegmentedControl *)sender {
    switch (sender.selectedSegmentIndex) {
        case 0:
        {
            memoryBankType = ASR033WMemoryBank_Reserved;
            self.startWriteAddressTextField.text = @"0";
        }
            break;
        case 1:
        {
            memoryBankType = ASR033WMemoryBank_EPC;
            self.startWriteAddressTextField.text = @"2";
        }
            break;
        case 2:
        {
            memoryBankType = ASR033WMemoryBank_TID;
            self.startWriteAddressTextField.text = @"0";
        }
            break;
        case 3:
        {
            memoryBankType = ASR033WMemoryBank_User;
            self.startWriteAddressTextField.text = @"0";
        }
            break;
        default:
            break;
    }
}
#pragma mark - System
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
#pragma mark - Private
- (void)dismissHUD {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [SVProgressHUD dismiss];
    }];
}
@end
