//
//  PTConnectVC.m
//  WirelessPrinter
//
//  Created by midmirror on 16/2/24.
//  Copyright © 2016年 midmirror. All rights reserved.
//

#import "WiFiController.h"
#import <PrinterSDK/PrinterSDK.h>
#import <SystemConfiguration/CaptiveNetwork.h>
#import "ProgressHUD.h"

#define SCREEN_WIDTH [UIScreen mainScreen].bounds.size.width
#define SCREEN_HEIGHT [UIScreen mainScreen].bounds.size.height

@interface WiFiController()

@property(strong,nonatomic,readwrite) UITableView *tableView;
@property(strong,nonatomic,readwrite) NSArray *wifiPrinters;
@property(strong,nonatomic,readwrite) PTRouter *router;

/** 网卡的 MAC 对应的产商 */
@property(strong,nonatomic,readwrite) NSMutableDictionary *ouiBaseDict;

@end

@implementation WiFiController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];
    _tableView.dataSource = self;
    _tableView.delegate = self;
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_tableView];
    
    UIBarButtonItem *scanItem = [[UIBarButtonItem alloc] initWithTitle:@"Scan" style:UIBarButtonItemStyleDone target:self action:@selector(scanWiFiPrinter)];
    self.navigationItem.rightBarButtonItem = scanItem;
}

- (void)closeView {
    
    [ProgressHUD dismiss];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.  ·
}

#pragma mark - UITableViewDataSource

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *iden = @"connectCell";
    UITableViewCell *tableCell;
    
    tableCell = [tableView dequeueReusableCellWithIdentifier:iden];
    if (tableCell == nil) {
        tableCell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:iden];
    }
    
    tableCell.textLabel.text = @"";
    tableCell.detailTextLabel.text = @"";
    tableCell.imageView.image = nil;
    tableCell.accessoryView = nil;

    if (self.router.connected) {
        
        PTPrinter *printer = self.wifiPrinters[indexPath.row];
        NSString *company = self.ouiBaseDict[printer.macKey];
        
        if ([printer.ip isEqualToString:self.router.localIP]) { // 如果搜索到的 IP 是本机（iOS） IP
            NSString *thisDevice = [[NSString alloc] initWithFormat:@"%@ (%@)",company,[[UIDevice currentDevice] name]];
            tableCell.textLabel.text = thisDevice;
        } else {
            tableCell.textLabel.text = company;
        }
        tableCell.detailTextLabel.text = [NSString stringWithFormat:@"%@ %@",printer.mac, printer.ip];
    }
    
    return tableCell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//取消选中 cell
    
    PTPrinter *printer = self.wifiPrinters[indexPath.row];
    NSString *company = self.ouiBaseDict[printer.macKey];
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Warning"
                                                                   message:[NSString stringWithFormat:@"Connect: %@  Port:9100",printer.ip]
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Connect" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        [PTDispatcher share].printerConnected.name = [[NSString alloc] initWithFormat:@"%@ %@",printer.ip,company];
        [ProgressHUD show:printer.ip];
        
        printer.port = @"9100";
        if ([PTDispatcher share].printerConnected) {
            [[PTDispatcher share] unconnectPrinter:[PTDispatcher share].printerConnected];
        }
        [[PTDispatcher share] connectPrinter:printer];
        [[PTDispatcher share] whenConnectSuccess:^{
            [ProgressHUD showSuccess:@"Connected"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [[PTDispatcher share] whenConnectFailure:^{
            [ProgressHUD showError:@"连接失败"];
        }];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - WiFi Detect

- (void)initWiFiDataBase {
    
    // 载入 OUI 查询字典，以查询网卡制造商
    if (!self.ouiBaseDict) {
        self.ouiBaseDict = [[NSMutableDictionary alloc] init];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"oui" ofType:@"plist"];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            
            self.ouiBaseDict = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
            [self.tableView reloadData];
        });
    }
}

#pragma -mark wifi scan delegate

- (void)scanWiFiPrinter {
    
    [self initWiFiDataBase];
    [ProgressHUD show:@"扫描网段IP..."];
    self.router = [[PTRouter alloc] init];
    if (self.router.connected) {
        [[PTDispatcher share] scanWiFi:^(NSDictionary *printerDict) {
            [ProgressHUD showSuccess:@"扫描成功"];
            
            self.wifiPrinters = printerDict.allValues;
            [self.tableView reloadData];
        }];
    } else {
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Unconnect WiFi"
                                                                       message:@"please active WiFi to connect printer"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        NSURL *url = [NSURL URLWithString:@"APP-Prefs:root=WIFI"];
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"Active" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[UIApplication sharedApplication] openURL:url];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        
        if ([[UIApplication sharedApplication] canOpenURL:url])
        {
            [alert addAction:defaultAction];
        }
        [alert addAction:cancelAction];
        
        [self presentViewController:alert animated:YES completion:nil];
    }
}

@end
