//
//  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 "SVProgressHUD.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:NSLocalizedString(@"scan", @"") style:UIBarButtonItemStyleDone target:self action:@selector(scanWiFiPrinters)];
    self.navigationItem.rightBarButtonItem = scanItem;
}

- (void)closeView {
    
    [SVProgressHUD 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.ip];
        
        if ([printer.ip isEqualToString:self.router.localIP]) {
            NSString *thisDevice = [[NSString alloc] initWithFormat:@"%@ (%@)",company,[[UIDevice currentDevice] name]];
            tableCell.textLabel.text = thisDevice;
        } else {
            tableCell.textLabel.text = company;
        }

        tableCell.detailTextLabel.text = [NSString stringWithFormat:@"%@", printer.ip];
    }
    
    return tableCell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    PTPrinter *printer = self.wifiPrinters[indexPath.row];
    NSString *company = self.ouiBaseDict[printer.ip];
    
    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"Tips"
                                                                   message:[NSString stringWithFormat:@"IP: %@  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];
        [SVProgressHUD showWithStatus:printer.ip];
        printer.port = @"9100";
        if ([PTDispatcher share].printerConnected) {
            [[PTDispatcher share] unconnectPrinter:[PTDispatcher share].printerConnected];
        }
        
        [[PTDispatcher share] connectPrinter:printer];
        
        [[PTDispatcher share] whenConnectSuccess:^{
            PTDispatcher.share.printerConnected = printer;
            [SVProgressHUD showSuccessWithStatus:@"connect Success"];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancle" 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];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
            });
        });
    }
}

#pragma -mark wifi scan delegate

- (void)scanWiFiPrinters {
    
//    [self initWiFiDataBase];
    self.router = [[PTRouter alloc] init];
    if (self.router.connected) {
        [SVProgressHUD showWithStatus:NSLocalizedString(@"IP network segment is scan, please be patient", @"")];
        [[PTDispatcher share] scanWiFi:^(NSMutableArray<PTPrinter *> *printerArray) {
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"Scan success", @"")];
            self.wifiPrinters = printerArray;
            [self.tableView reloadData];
        }];
    } else {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"Tips", @"")
                                                                       message:NSLocalizedString(@"Please connect printer WiFi in system setting", @"")
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        NSURL *url = [NSURL URLWithString:@"APP-Prefs:root=WIFI"];
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"System settings", @"") style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [[UIApplication sharedApplication] openURL:url];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"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
