//
//  SearchViewController.m
//  ASR033WDemo
//
//  Created by Songxueqian on 2024/12/23.
//

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

@interface SearchViewController ()<ASR033WDelegate, UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation SearchViewController
{
    ASR033W *asr033w;
    NSMutableArray *dataArray;
    System *system;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    system = [System sharedSystem];
    dataArray = [[NSMutableArray alloc] init];
    asr033w = [ASR033W sharedInstance];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    asr033w.delegate = self;
    [SVProgressHUD showWithStatus:@"Searching..."];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    asr033w.delegate = nil;
}
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [asr033w setSearchDeviceTimeout:[[system getStopTime] intValue]];
    [asr033w startSearchDevice];
}
#pragma mark - Action
- (IBAction)onClickDoneBarItem:(UIBarButtonItem *)sender {
    [self.view endEditing:YES];
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"" message:@"Search" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.placeholder = @"StopTime(10~60s)";
        textField.keyboardType = UIKeyboardTypeNumberPad;
        textField.text = [self->system getStopTime];
    }];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self->dataArray removeAllObjects];
        [self.tableView reloadData];
        UITextField *textField = alertVC.textFields.firstObject;
        NSTimeInterval time = [textField.text intValue];
        [self->system setStopTime:[NSString stringWithFormat:@"%d", (int)time]];
        [SVProgressHUD showWithStatus:@"Searching..."];
        [self->asr033w setSearchDeviceTimeout:time];
        [self->asr033w startSearchDevice];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableViewCell"];
    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"tableViewCell"];
    }
    NSString *string = [dataArray objectAtIndex:indexPath.row];
    cell.textLabel.text = [self getInformation:string];
    cell.textLabel.numberOfLines = 0;
    [cell.textLabel sizeToFit];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *string = [dataArray objectAtIndex:indexPath.row];
    NSArray *array = [string componentsSeparatedByString:@"\n"];
    if (array.count == 3) {
        NSString *ipString = [array firstObject];
        if (ipString && ipString.length > 0) {
            if (self.delegate && [self.delegate respondsToSelector:@selector(searchIP:port:)]) {
                int port = 0;
                if ([system getConnectMethod] == ConnectMethod_TCP) {
                    port = [[system getPort] intValue];
                } else {
                    port = [[system getMQTTPort] intValue];
                }
                [self.delegate searchIP:ipString port:port];
            }
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - ASR033WDelegate
- (void)receivedASR033WSearchInformation:(NSDictionary *)information isFinish:(BOOL)isFinish{
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        if(isFinish == YES)
        {
            if([SVProgressHUD isVisible]){
                [SVProgressHUD dismiss];
            }
            if ([self->dataArray count]>0) {
                [self.tableView reloadData];
            } else {
                UIAlertController * alert = [UIAlertController alertControllerWithTitle:@"Search" message:@"Not found Devices" preferredStyle:UIAlertControllerStyleAlert];
                [alert addAction:[[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:nil] init]];
                [self presentViewController:alert animated:YES completion:nil];
            }
        } else {
            NSString *ip = [information valueForKey:SEARCH_HOST_SERVER_IP];
            NSString *ipString = [NSString stringWithFormat:@"%@", ip];
            
            NSString *serialNumber = [information valueForKey:SEARCH_RFID_READER_INFORMATION];
            NSString *serialNumberString = [NSString stringWithFormat:@"%@", serialNumber];
            
            NSString *mac = [information valueForKey:SEARCH_MAC];
            NSString *macString = [NSString stringWithFormat:@"%@",mac];
            
            NSString *newString = [NSString stringWithFormat:@"%@\n%@\n%@", ipString, serialNumberString, macString];
            if (![self->dataArray containsObject:newString]) {
                [self->dataArray addObject:newString];
            }
        }
    }];
}
#pragma mark - Private
- (void)dismissHUD {
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        [SVProgressHUD dismiss];
    }];
}
- (NSString *)getInformation:(NSString *)information {
    NSArray *array = [information componentsSeparatedByString:@"\n"];
    if (array.count == 3) {
        NSString *ip = [NSString stringWithFormat:@"IP:%@", [array firstObject]];
        NSString *serialNumber = [NSString stringWithFormat:@"RFID module manufacture number:%@", [array objectAtIndex:1]];
        NSString *mac = [NSString stringWithFormat:@"MAC:%@", [array lastObject]];
        NSString *newString = [NSString stringWithFormat:@"%@\n%@\n%@", ip, serialNumber, mac];
        return newString;
    }
    return @"";
}
@end
