//
//  ICNetworkSpeedViewController.m
//  superCleaner
//
//  Created by Mazy on 2020/7/30.
//  Copyright © 2020 Mazy. All rights reserved.
//

#import "ICNetworkSpeedViewController.h"
#import "superCleaner-Swift.h"
#import "MeasurNetTools.h"
#import "QBTools.h"
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <net/if_dl.h>
#import "STDPingServices.h"
#import <SystemConfiguration/CaptiveNetwork.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

@interface ICNetworkSpeedViewController ()

@property (weak, nonatomic) IBOutlet UIButton *startButton;

@property (nonatomic, assign) CGFloat minValue;
@property (nonatomic, assign) CGFloat maxValue;
@property (nonatomic, assign) CGFloat currentValue;

@property(nonatomic, strong) STDPingServices  *pingServices;

@property (strong, nonatomic) SCNetWorkDashBoardView * board;

@property (weak, nonatomic) IBOutlet UIView * boardBgView;

@property (nonatomic, assign) BOOL detectionBegining;

@property (weak, nonatomic) IBOutlet UILabel *timeMillisecondsLabel;
@property (weak, nonatomic) IBOutlet UILabel *uploadValueLabel;
@property (weak, nonatomic) IBOutlet UILabel *downloadValueLabel;

@property (weak, nonatomic) IBOutlet UIImageView * timeMillisecondsImV;
@property (weak, nonatomic) IBOutlet UIImageView * uploadValueImV;
@property (weak, nonatomic) IBOutlet UIImageView * downloadValueImV;

@end

@implementation ICNetworkSpeedViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = ICLocalized(@"InternetSpeedTest");

    [self.view layoutIfNeeded];
    [self.view layoutSubviews];
    
    [self setupUI];
    
    self.board = [[SCNetWorkDashBoardView alloc] initWithFrame:self.boardBgView.bounds];
    [self.boardBgView addSubview:self.board];
    self.board.mbpsValue = 0;
    self.board.progressValue = 0;
    [self observationNetwork];
    
    self.minValue = 0;
    self.maxValue = 10;
    self.currentValue = 0;
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.pingServices cancel];
}

- (void)setDetectionBegining:(BOOL)detectionBegining{
    _detectionBegining = detectionBegining;
    
    _timeMillisecondsLabel.hidden = !_detectionBegining;
    _uploadValueLabel.hidden = !_detectionBegining;
    _downloadValueLabel.hidden = !_detectionBegining;
    
    _timeMillisecondsImV.hidden = _detectionBegining;
    _uploadValueImV.hidden = _detectionBegining;
    _downloadValueImV.hidden = _detectionBegining;
}

- (void)pingActionFired {
    
    self.pingServices = [STDPingServices startPingAddress: @"https://www.baidu.com" monitorTime: 5 callbackHandler:^(STDPingItem *pingItem, NSArray *pingItems) {
        if (pingItem.status != STDPingStatusFinished) {
            NSLog(@"-----%@", pingItem.description);
        } else {
            NSArray *results = [STDPingItem statisticsWithPingItems:pingItems];
            NSLog(@"%@", results);
            self.timeMillisecondsLabel.text = results.lastObject;
        }
    }];
}

- (IBAction)startNetworkSpeedTest:(UIButton *)sender {
    
    self.detectionBegining = YES;
    
    self.startButton.userInteractionEnabled = false;
    [self.startButton setTitle: @"测速中" forState:UIControlStateNormal];
    [self pingActionFired];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self startTestSpeed];
        });
    });
}

- (void)startTestSpeed {

    self.downloadValueLabel.text = @"0.00MB/S";
    self.uploadValueLabel.text = @"0.00MB/S";
    __weak typeof(self) weakSelf = self;
    MeasurNetTools * meaurNet = [[MeasurNetTools alloc] initWithblock:^(float speed) {
        NSString* speedStr = [NSString stringWithFormat:@"%@/S", [QBTools formattedFileSize:speed]];
        NSLog(@"即使速度%@", speedStr);
        NSLog(@"上行速度%@", [weakSelf getInterfaceBytes]);
        weakSelf.downloadValueLabel.text = speedStr;
        weakSelf.uploadValueLabel.text = [weakSelf getInterfaceBytes];

        CGFloat networkSpeed = 0.0;
        NSString * unit;
        if ([[QBTools formattedFileSize:speed] containsString:@"KB"]) {
            networkSpeed = [[QBTools formattedFileSize:speed] floatValue] / 1024;
            unit = @"KB";
        }
        if ([[QBTools formattedFileSize:speed] containsString:@"bytes"]) {
            networkSpeed = [[QBTools formattedFileSize:speed] floatValue] / 1024 / 1024;
            unit = @"bytes";
        }
        if ([[QBTools formattedFileSize:speed] containsString:@"GB"]) {
            networkSpeed = [[QBTools formattedFileSize:speed] floatValue] * 1024;
            unit = @"GB";
        } else {
            networkSpeed = [[QBTools formattedFileSize:speed] floatValue];
            unit = @"MB";
        }
        networkSpeed = [speedStr floatValue];
        [weakSelf refreshDownloadDashboard: networkSpeed];
        
        self.board.speedUnit = unit;
        self.board.mbpsValue = networkSpeed;
        
    } finishMeasureBlock:^(float speed) {
        NSString* speedStr = [NSString stringWithFormat:@"%@/S", [QBTools formattedFileSize:speed]];
        NSLog(@"平均速度为：%@",speedStr);
        NSLog(@"相当于带宽：%@",[QBTools formatBandWidth:speed]);
        self.startButton.userInteractionEnabled = true;
        [self.startButton setTitle: @"重新测速" forState:UIControlStateNormal];
    } failedBlock:^(NSError *error) {
        self.startButton.userInteractionEnabled = true;
        [self.startButton setTitle: @"重新测速" forState:UIControlStateNormal];
    }];
    
    [meaurNet startMeasur];
}

- (void)refreshDownloadDashboard:(CGFloat)currentValue {
    // 控制范围
    if (currentValue > self.maxValue) {
        self.currentValue = self.maxValue;
    }
    if (currentValue <= self.minValue) {
        self.currentValue = self.minValue;
    }
    self.currentValue = currentValue;

    // 百分比
    CGFloat percent = (currentValue - self.minValue) / (self.maxValue - self.minValue);

    if (percent > 1) {
        percent = 1;
    }
    
    self.board.progressValue = percent;
}

- (void)refreshUploadDashboard:(CGFloat)currentValue {
    // 控制范围
    if (currentValue > self.maxValue) {
        self.currentValue = self.maxValue;
    }
    if (currentValue <= self.minValue) {
        self.currentValue = self.minValue;
    }
    self.currentValue = currentValue;

    // 百分比
    CGFloat percent = (currentValue - self.minValue) / (self.maxValue - self.minValue);

    self.board.mbpsValue = percent;
}

/*获取网络流量信息*/
- (NSString *) getInterfaceBytes {
    struct ifaddrs *ifa_list = 0, *ifa;
    if (getifaddrs(&ifa_list) == -1) {
        return 0;
    }
    uint32_t iBytes = 0;
    uint32_t oBytes = 0;
    for (ifa = ifa_list; ifa; ifa = ifa->ifa_next) {
        if (AF_LINK != ifa->ifa_addr->sa_family)
            continue;
        if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))
            continue;
        if (ifa->ifa_data == 0)
            continue;
        /* Not a loopback device. */
        if (strncmp(ifa->ifa_name, "lo", 2)) {
            struct if_data *if_data = (struct if_data *)ifa->ifa_data;
            //下行
            iBytes += if_data->ifi_ibytes;
            //上行
            oBytes += if_data->ifi_obytes;
        }
    }
    freeifaddrs(ifa_list);
//    NSLog(@"\n[getInterfaceBytes-Total]%@,%@",[QBTools formattedFileSize:iBytes/1024], [QBTools formattedFileSize:oBytes/1024]);
//    NSLog(@"------%@", [[QBTools formattedFileSize:oBytes/1024] substringToIndex:4]);
    
    NSString *uploadValue = [[QBTools formattedFileSize:oBytes/1024] substringToIndex:4];
    
//    NSLog(@"========= %.2f", [uploadValue doubleValue] / 10);
//    self.uploadBoardView.progressValue = [uploadValue doubleValue] / 10;
    
    return [NSString stringWithFormat:@"%@/S", [QBTools formattedFileSize:oBytes/1024]];
}

/// 监听网络状态
- (void)observationNetwork {
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                NSLog(@"未知网络");
                self.board.name = @"未知网络";
                break;
            case AFNetworkReachabilityStatusNotReachable:
                NSLog(@"无网络");
                self.board.name = @"无网络";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                NSLog(@"WiFi网络");
                self.board.name = [NSString stringWithFormat:@"%@\n%@", @"Wi-Fi", [self ssid]];
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                NSLog(@"移动网络");
                self.board.name = [self networkStatus];
                break;
            default:
                break;
        }
    }];
    [manager startMonitoring];
}

- (NSString *)networkStatus{
    
    NSArray *typeStrings2G = @[CTRadioAccessTechnologyEdge,
        CTRadioAccessTechnologyGPRS,
        CTRadioAccessTechnologyCDMA1x];
    
    NSArray *typeStrings3G = @[CTRadioAccessTechnologyHSDPA,
        CTRadioAccessTechnologyWCDMA,
        CTRadioAccessTechnologyHSUPA,
        CTRadioAccessTechnologyCDMAEVDORev0,
        CTRadioAccessTechnologyCDMAEVDORevA,
        CTRadioAccessTechnologyCDMAEVDORevB,
        CTRadioAccessTechnologyeHRPD];
 
    NSArray *typeStrings4G = @[CTRadioAccessTechnologyLTE];
 
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7.0) {
        CTTelephonyNetworkInfo *teleInfo= [[CTTelephonyNetworkInfo alloc] init];
        NSString *accessString = teleInfo.currentRadioAccessTechnology;
        if ([typeStrings4G containsObject:accessString]) {
            NSLog(@"4G网络");
            return @"4g";
        } else if ([typeStrings3G containsObject:accessString]) {
            NSLog(@"3G网络");
            return @"3g";
        } else if ([typeStrings2G containsObject:accessString]) {
            NSLog(@"2G网络");
            return @"2g";
        } else {
            NSLog(@"未知网络");
            return @"unkown";
        }
    } else {
        NSLog(@"未知网络");
        return @"unkown";
    }
    return @"unkown";
}

- (NSString *)ssid{
    NSString *ssid = @"Not Found";
    CFArrayRef myArray = CNCopySupportedInterfaces();
    if (myArray != nil) {
        CFDictionaryRef myDict = CNCopyCurrentNetworkInfo(CFArrayGetValueAtIndex(myArray, 0));
        if (myDict != nil) {
            NSDictionary *dict = (NSDictionary*)CFBridgingRelease(myDict);
            ssid = [dict valueForKey:@"SSID"];
        }
    }
    return ssid;
}

@end
