#import "MainViewController.h"
#import "UserlDefind.h"
#import "iBeaconConfigViewController.h"

@interface MainViewController ()
{
    UILabel * _tvDeviceCount;
    UIButton * _bnScan;
    UIButton * _bnClear;
    UITableView * _deviceTableView;
    NSMutableArray * _deviceList;
}

@end

@implementation DeviceInfo

- (instancetype)init {
    self = [super init];
    if (self) {
        _scanTimeList = [[NSMutableArray alloc] initWithCapacity:5];
    }
    return self;
}

- (int)getAverageInterval {
    if (_scanTimeList.count < 2) {
        return 0;
    }
    
    long long totalInterval = 0;
    for (int i = 1; i < _scanTimeList.count; i++) {
        long long current = [_scanTimeList[i] longLongValue];
        long long prev = [_scanTimeList[i-1] longLongValue];
        totalInterval += current - prev;
    }
    
    return (int)(totalInterval / (_scanTimeList.count - 1));
}

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor colorWithRed:0.9 green:0.9 blue:0.9 alpha:1.0]];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
    
    if (@available(iOS 13.0, *)) {
        UIStatusBarManager *statusBarManager = [UIApplication sharedApplication].keyWindow.windowScene.statusBarManager;
        if (statusBarManager) {
            UIView *statusBar = [[UIView alloc] initWithFrame:statusBarManager.statusBarFrame];
            statusBar.backgroundColor = [UIColor whiteColor];
            [self.navigationController.navigationBar.superview addSubview:statusBar];
        }
    } else {
        UIView *statusBar = [[UIView alloc] initWithFrame:[UIApplication sharedApplication].statusBarFrame];
        statusBar.backgroundColor = [UIColor whiteColor];
        [self.navigationController.navigationBar.superview addSubview:statusBar];
    }
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    titleLabel.text = NSLocalizedString(@"JoywayBeacon", @"");
    titleLabel.font = [UIFont systemFontOfSize:17];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
    
    [self bindUI];
    
    _deviceList = [[NSMutableArray alloc] init];
    
    [BT initModuleWithReadingRssiTimeInterval:1.0];
    [BT listenBTEvent:self listen:TRUE];
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleDefault;
}

- (void)bindUI {
    int left = 10;
    int top = 10;
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, top, SCREEN_WIDTH, 44)];
    
    _tvDeviceCount = [[UILabel alloc] initWithFrame:CGRectMake(left, 10, 100, 24)];
    _tvDeviceCount.font = [UIFont systemFontOfSize:14];
    _tvDeviceCount.text = [NSString stringWithFormat:NSLocalizedString(@"%lu 设备", @""), (unsigned long)0];
    [headerView addSubview:_tvDeviceCount];
    
    int btnWidth = 100;
    int btnHeight = 44;
    int btnGap = 10;
    int btnStartX = SCREEN_WIDTH - left - btnWidth * 2 - btnGap;
    
    _bnScan = [[UIButton alloc] initWithFrame:CGRectMake(btnStartX, 0, btnWidth, btnHeight)];
    [_bnScan setTitle:NSLocalizedString(@"扫描", @"") forState:UIControlStateNormal];
    [_bnScan setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_bnScan.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [self setButtonStyle:_bnScan type:@"neutral"];
    [_bnScan addTarget:self action:@selector(onBnScanClicked) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:_bnScan];
    
    _bnClear = [[UIButton alloc] initWithFrame:CGRectMake(btnStartX + btnWidth + btnGap, 0, btnWidth, btnHeight)];
    [_bnClear setTitle:NSLocalizedString(@"清空", @"") forState:UIControlStateNormal];
    [_bnClear setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [_bnClear.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [self setButtonStyle:_bnClear type:@"negative"];
    [_bnClear addTarget:self action:@selector(onBnClearClicked) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:_bnClear];
    
    [self.view addSubview:headerView];
    
    _deviceTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, top + 50, SCREEN_WIDTH, SCREEN_HEIGHT - top - 50 - 64)];
    _deviceTableView.dataSource = self;
    _deviceTableView.delegate = self;
    _deviceTableView.rowHeight = 80;
    _deviceTableView.backgroundColor = [UIColor whiteColor];
    _deviceTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    [self.view addSubview:_deviceTableView];
}

- (void)setButtonStyle:(UIButton *)button type:(NSString *)type {
    button.layer.cornerRadius = 8;
    button.layer.borderWidth = 0.5;
    button.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    
    if ([type isEqualToString:@"neutral"]) {
        button.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.1];
    } else if ([type isEqualToString:@"negative"]) {
        button.backgroundColor = [[UIColor redColor] colorWithAlphaComponent:0.1];
    } else if ([type isEqualToString:@"positive"]) {
        button.backgroundColor = [[UIColor greenColor] colorWithAlphaComponent:0.1];
    }
}

- (void)onBnScanClicked {
    if ([_bnScan.titleLabel.text isEqualToString:NSLocalizedString(@"扫描", @"")]) {
        [BT startScanAllowDuplicatesKey:YES serviceUUIDs:nil];
        [_bnScan setTitle:NSLocalizedString(@"停止", @"") forState:UIControlStateNormal];
    } else {
        [BT stopScan];
        [_bnScan setTitle:NSLocalizedString(@"扫描", @"") forState:UIControlStateNormal];
    }
}

- (void)onBnClearClicked {
    [_deviceList removeAllObjects];
    [_deviceTableView reloadData];
    _tvDeviceCount.text = [NSString stringWithFormat:NSLocalizedString(@"%lu 设备", @""), (unsigned long)0];
}

- (BOOL)matchesFilter:(Tag *)tag {
    if (!tag._name) {
        return NO;
    }
    NSString *name = tag._name;
    NSArray *prefixes = @[@"JW1400B", @"JW1401B", @"JW1404B", @"JW1405B", @"JW1407B", @"JW1409B", @"JoywayBeacon"];
    for (NSString *prefix in prefixes) {
        if ([name hasPrefix:prefix]) {
            return YES;
        }
    }
    return NO;
}

- (void)updateDeviceListWithTag:(Tag *)tag {
    NSString *mac = tag._mac;
    BOOL found = NO;
    
    for (DeviceInfo *device in _deviceList) {
        if ([device.mac isEqualToString:mac]) {
            device.name = tag._name;
            device.rssi = tag._rssi;
            
            long long currentTime = [[NSDate date] timeIntervalSince1970] * 1000;
            [device.scanTimeList addObject:[NSNumber numberWithLongLong:currentTime]];
            if (device.scanTimeList.count > 5) {
                [device.scanTimeList removeObjectAtIndex:0];
            }
            
            found = YES;
            break;
        }
    }
    
    if (!found) {
        DeviceInfo *newDevice = [[DeviceInfo alloc] init];
        newDevice.mac = mac;
        newDevice.name = tag._name;
        newDevice.rssi = tag._rssi;
        
        long long currentTime = [[NSDate date] timeIntervalSince1970] * 1000;
        [newDevice.scanTimeList addObject:[NSNumber numberWithLongLong:currentTime]];
        
        [_deviceList addObject:newDevice];
    }
    
    _tvDeviceCount.text = [NSString stringWithFormat:NSLocalizedString(@"%lu 设备", @""), (unsigned long)_deviceList.count];
    [_deviceTableView reloadData];
}



#pragma mark - UITableViewDataSource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellIdentifier = @"DeviceCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    
    DeviceInfo *device = _deviceList[indexPath.row];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, SCREEN_WIDTH - 130, 20)];
    nameLabel.font = [UIFont systemFontOfSize:16];
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.text = device.name;
    [cell.contentView addSubview:nameLabel];
    
    UILabel *macLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 35, SCREEN_WIDTH - 130, 18)];
    macLabel.font = [UIFont systemFontOfSize:12];
    macLabel.textColor = [UIColor grayColor];
    macLabel.text = device.mac;
    [cell.contentView addSubview:macLabel];
    
    UILabel *rssiLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 55, 80, 18)];
    rssiLabel.font = [UIFont systemFontOfSize:14];
    rssiLabel.textColor = [UIColor blackColor];
    rssiLabel.text = [NSString stringWithFormat:@"RSSI: %d", device.rssi];
    [cell.contentView addSubview:rssiLabel];
    
    int avgInterval = [device getAverageInterval];
    UILabel *intervalLabel = [[UILabel alloc] initWithFrame:CGRectMake(105, 55, SCREEN_WIDTH - 240, 18)];
    intervalLabel.font = [UIFont systemFontOfSize:14];
    intervalLabel.textColor = [UIColor blackColor];	
    intervalLabel.text = [NSString stringWithFormat:@"%dms", avgInterval];
    [cell.contentView addSubview:intervalLabel];
    
    UIButton *connectBtn = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 115, 18, 100, 44)];
    [connectBtn setTitle:NSLocalizedString(@"连接", @"") forState:UIControlStateNormal];
    [connectBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [connectBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [self setButtonStyle:connectBtn type:@"positive"];
    connectBtn.tag = indexPath.row;
    [connectBtn addTarget:self action:@selector(onConnectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    [cell.contentView addSubview:connectBtn];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)onConnectButtonClicked:(UIButton *)sender {
    int index = sender.tag;
    DeviceInfo *device = _deviceList[index];
    NSLog(@"[BT Log] Connecting to device: %@, name: %@", device.mac, device.name);
    iBeaconConfigViewController *vc = [[iBeaconConfigViewController alloc] init];
    vc.mac = device.mac;
    vc.name = device.name;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - BTEvtDelegate

- (void)onTagScaned:(NSString *)tagMac tag:(Tag *)tag advertisementData:(NSDictionary *)advertisementData {
    if ([self matchesFilter:tag]) {
        NSLog(@"[BT Log] Scanned device matching filter: mac=%@, name=%@, rssi=%d", tagMac, tag._name, tag._rssi);
        [self updateDeviceListWithTag:tag];
    }
}

- (void)onTagConnected:(NSString *)tagMac {
    NSLog(@"[BT Log] Connected to device: %@", tagMac);
}

- (void)onTagDisconnected:(NSString *)tagMac {
    NSLog(@"[BT Log] Disconnected from device: %@", tagMac);
}

- (void)onTagData:(NSString *)tagMac strData:(NSString *)strData byteData:(NSData *)byteData {
    NSLog(@"[BT Log] Received data from device: mac=%@, strData=%@, byteData length=%lu", tagMac, strData ?: @"nil", (unsigned long)byteData.length);
}

- (void)onTagRssiChanged:(NSString *)tagMac rssi:(int)rssi {
    NSLog(@"[BT Log] RSSI changed: mac=%@, rssi=%d", tagMac, rssi);
}

- (void)dealloc {
    [BT listenBTEvent:self listen:FALSE];
    [BT stopScan];
}

@end
