//
//  TcpDeviceController.m
//  JXPrinterDemo
//
//  Created by 贾俊伟 on 2022/6/23.
//

#import "TcpDeviceController.h"
#import <JXPrinter/JXPrinter.h>
#import "TcpCell.h"
#import "JXProgressHUD.h"
#import "MMLANScanner.h"
#import "MMDevice.h"

@interface TcpDeviceController ()<
JXSocketManagerDelegate,
MMLANScannerDelegate,
UITableViewDelegate,
UITableViewDataSource
>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *bottomBtn;
@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
@property (nonatomic, strong) NSMutableArray<NSString *> *ips;
@property (nonatomic, strong) JXSocketManager *socketManager;
@property (nonatomic,   copy) NSString *connectIp;
@property(nonatomic,strong)MMLANScanner *lanScanner;

@end

@implementation TcpDeviceController

static NSString * const cellId = @"cellId";

// YES为扫描所有活跃的IP(使用了MMLanScan) ,NO为扫描接收指定广播的IP
// YES for scanning all active IP addresses(use MMLanScan), NO for scanning and receiving specified broadcast IP addresses
static BOOL const scanAll = YES;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.bottomBtn];
    [self.bottomBtn addSubview:self.activityIndicator];
    [self.view addSubview:self.tableView];
    [self startScanPeripherals];
    [self addHeaderView];
}

- (void)addHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 88, [UIScreen mainScreen].bounds.size.width, 50)];
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(20, 0, 100, 40)];
    lb.text = @"连接端口:";
    lb.textColor = [UIColor blackColor];
    [headerView addSubview:lb];
    [headerView addSubview:self.textField];
    [self.view addSubview:headerView];
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.activityIndicator.frame = CGRectMake(30, 0, 50, 50);
    self.bottomBtn.frame = CGRectMake(40, [UIScreen mainScreen].bounds.size.height - 100, [UIScreen mainScreen].bounds.size.width - 80, 50);
    self.tableView.frame = CGRectMake(0, 130, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height - 250);
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    NSLog(@"%s", __func__);
    if (scanAll) {
        [self.lanScanner stop];
    } else {
        [self.socketManager stopScan];
    }
}

#pragma mark - JXSocketManagerDelegate

- (void)manager:(JXSocketManager *)manager scanDidFindNewIP:(NSString *)ip port:(int)port mfg:(NSString *)mfg model:(NSString *)model cmd:(NSString *)cmd {
    if (![self.ips containsObject:ip]) {
        [self.ips addObject:ip];
    }
    [self.tableView reloadData];
}

- (void)scanDidFinish:(JXSocketManager *)manager {
    [self.bottomBtn setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
    [self.activityIndicator stopAnimating];
}

- (void)manager:(JXSocketManager *)manager didConnectToHost:(NSString *)host port:(uint16_t)port {
    NSLog(@"%s", __func__);
    NSLog(@"连接成功");
    [JXProgressHUD hideHUD];
    [[NSUserDefaults standardUserDefaults] setObject:host forKey:@"ip"];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)connectTimeout:(JXSocketManager *)manager {
    NSLog(@"连接超时");
    [JXProgressHUD hideHUD];
}

- (void)manager:(JXSocketManager *)manager didWriteDataWithTag:(long)tag {
    NSLog(@"%s-%ld", __func__, tag);
}

- (void)manager:(JXSocketManager *)manager didDisconnectwithError:(NSError *)err {
    [self.tableView reloadData];
}

#pragma mark - MMLANScannerDelegate

- (void)lanScanDidFindNewDevice:(MMDevice *)device {
    if (![self.ips containsObject:device.ipAddress]) {
        [self.ips addObject:device.ipAddress];
    }
    [self.tableView reloadData];
}

- (void)lanScanDidFinishScanningWithStatus:(MMLanScannerStatus)status {
    [self.bottomBtn setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
    [self.activityIndicator stopAnimating];
}

- (void)lanScanProgressPinged:(float)pingedHosts from:(NSInteger)overallHosts {
    NSLog(@"%s", __func__);
}

- (void)lanScanDidFailedToScan {
    NSLog(@"%s", __func__);
}

#pragma UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.ips.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    TcpCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.ip = self.ips[indexPath.row];
    cell.connected = self.socketManager.isConnected && [self.connectIp isEqual:self.ips[indexPath.row]];
    __weak typeof(self) weakSelf = self;
    cell.connectBlock = ^(BOOL isConnect) {
        if (isConnect) {
            if (weakSelf.socketManager.isConnected) {
                [weakSelf.socketManager disconnect];
            }
            [weakSelf.tableView reloadData];
        } else {
            [JXProgressHUD showHUD];
            if ([JXBleManager bleManager].isConnectBle) {
                [[JXBleManager bleManager] disconnectPeripheral:[JXBleManager bleManager].connectedPeripheral];
            }
            // 发起连接的命令
            [weakSelf.socketManager connectToIPAddress:weakSelf.ips[indexPath.row] onPort:9100 timeout:10];
        }
    };
    return cell;
}

#pragma mark - Utils

- (void)startScanPeripherals {
    self.connectIp = [[NSUserDefaults standardUserDefaults] objectForKey:@"ip"];
    [self.ips removeAllObjects];
    [self.tableView reloadData];
    if (scanAll) {
        [self.lanScanner start];
    } else {
        // 扫描拥有指定服务的外设
        [self.socketManager startScanWithTimeout:10];
    }
    
    [self.bottomBtn setTitle:NSLocalizedString(@"Stop", nil) forState:UIControlStateNormal];
    [self.activityIndicator startAnimating];
}

- (void)p_stopScanPeripherals {
    [self.socketManager stopScan];
    [self.bottomBtn setTitle:NSLocalizedString(@"Scan", nil) forState:UIControlStateNormal];
    [self.activityIndicator stopAnimating];
}

- (void)bottomBtnClick {
    if (self.socketManager.isScanning) {
        [self p_stopScanPeripherals];
    } else {
        [self startScanPeripherals];
    }
}

#pragma mark - Getter

- (NSMutableArray<NSString *> *)ips {
    if (!_ips) {
        _ips = [[NSMutableArray alloc] init];
    }
    return _ips;
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] init];
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.rowHeight = 60;
        _tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
        [_tableView registerNib:[UINib nibWithNibName:NSStringFromClass([TcpCell class]) bundle:nil] forCellReuseIdentifier:cellId];
    }
    return _tableView;
}

- (UIButton *)bottomBtn {
    if (!_bottomBtn) {
        _bottomBtn = [[UIButton alloc] init];
        _bottomBtn.backgroundColor = [UIColor blueColor];
        [_bottomBtn addTarget:self action:@selector(bottomBtnClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _bottomBtn;
}

- (UITextField *)textField {
    if (!_textField) {
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(120, 0, 100, 40)];
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        _textField.text = @"9100";
    }
    return _textField;
}

- (UIActivityIndicatorView *)activityIndicator {
    if (!_activityIndicator) {
        _activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    }
    return _activityIndicator;
}

- (JXSocketManager *)socketManager {
    if (!_socketManager) {
        _socketManager = [JXSocketManager manager];
        _socketManager.delegate = self;
    }
    return _socketManager;
}

- (MMLANScanner *)lanScanner {
    if (!_lanScanner) {
        _lanScanner = [[MMLANScanner alloc] initWithDelegate:self];
    }
    return _lanScanner;
}

@end
