//
//  PDWiFiViewController.swift
//  PrinterDemo
//
//  Created by ios on 2019/9/9.
//  Copyright © 2019 XiamenHY. All rights reserved.
//

import UIKit
import PrinterSDK
import CoreLocation
import PrinterSDK

class PDWiFiViewController: PDBaseViewController {
    
    lazy var tableView : UITableView = {
        let temp = UITableView.init(frame: .zero, style: .grouped)
        temp.delegate = self
        temp.dataSource = self
        temp.backgroundColor = .white
        temp.rowHeight = 60
        temp.showsVerticalScrollIndicator = false
        temp.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
        return temp
    }()
    
    var ports = [S1UdpLanTarget]()
    
    let configurator = S1UdpNetConfig()
    
    var iden: String?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "WiFi".localized
        view.addSubview(tableView)
        tableView.snp.makeConstraints {
            $0.edges.equalTo(self.view.usnp.edges)
        }
        do {
            iden = try configurator.startSearch(-1, discovePortBlock: { [weak self] hotspot in
                if let index = self?.ports.firstIndex(where: { $0.ip == hotspot.ip }) {
                    self?.ports[index] = hotspot
                }else {
                    self?.ports.append(hotspot)
                }
                self?.tableView.reloadData()
            }, searchTimeoutBlock: { [weak self] in
                self?.show("搜索结束".localized)
            }, socketDisconnectedBlock: { [weak self] error in
                self?.show(String.init(format: "搜索失败: %@".localized, String(describing: error)))
            })
        } catch {
            self.show(String.init(format: "搜索失败: %@".localized, String(describing: error)))
        }
    }
    
    deinit {
        if let iden = iden {
            configurator.stopSearch(iden)
        }
    }

}

extension PDWiFiViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return ports.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        var cell = tableView.dequeueReusableCell(withIdentifier: "iden")
        if cell == nil {
            cell = UITableViewCell.init(style: UITableViewCell.CellStyle.subtitle, reuseIdentifier: "iden")
        }
        cell?.textLabel?.text = ports[indexPath.row].name
        cell?.detailTextLabel?.text = ports[indexPath.row].ip
        
        cell?.textLabel?.textColor = UIColor.black
        cell?.detailTextLabel?.textColor = UIColor.titleColor
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return "Pls. select a corresponding IP".localized
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 45.0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 60.0
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let port = ports[indexPath.row]
        let target = RYSocketAccessory(port.ip, port: 9100)
        self.tryAddPrinter(target)
    }
}


class XMDeviceSetting {

    static func openSettingAlert(message: String, cancelClosure: (() -> Void)? = nil) {
        
        guard let rootVC = PDAppWindow.rootViewController else { return }
        if let url = URL.init(string: "App-Prefs:root"), UIApplication.shared.canOpenURL(url) {
            rootVC.bk_presentDecisionAlertController(title: "Tips".localized, message: message, decisionTitle: "Setting".localized, decisionClosure: { (_) in
                UIApplication.shared.openURL(url)
            }, cancelClosure: { (_) in
                cancelClosure?()
            })
        }else if let url = URL.init(string: "Prefs:root"), UIApplication.shared.canOpenURL(url) {
            rootVC.bk_presentDecisionAlertController(title: "Tips".localized, message: message, decisionTitle: "Setting".localized, decisionClosure: { (_) in
                UIApplication.shared.openURL(url)
            }, cancelClosure: { (_) in
                cancelClosure?()
            })
        }else {
            rootVC.bk_presentDecisionAlertController(title: "Tips".localized, message: message, decisionTitle: "Setting".localized, decisionClosure: { (_) in
                
            }, cancelClosure: { (_) in
                cancelClosure?()
            })
        }
    }
    
    static func openSettings() {
        
        if let url = URL.init(string: "App-Prefs:root"), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.openURL(url)
        }else if let url = URL.init(string: "Prefs:root"), UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.openURL(url)
        }
    }

}
