//
//  PDWiFiScanViewController.swift
//  PrinterDemo
//
//  Created by Wencai Luo on 2022/6/22.
//  Copyright © 2022 ChinaPL. All rights reserved.
//

import UIKit
import PrinterSDK

class PDWiFiScanViewController: PDBaseViewController {

    private var dataSources = [PTPrinter]()
    
    lazy var tableView : UITableView = {
        let temp = UITableView.init(frame: .zero, style: .grouped)
        temp.delegate = self
        temp.dataSource = self
        temp.backgroundColor = .white
        temp.showsVerticalScrollIndicator = false
        temp.separatorStyle = UITableViewCell.SeparatorStyle.singleLine
        return temp
    }()
    
    private lazy var rightItem: UIBarButtonItem = {
        return UIBarButtonItem(title: "Scanning".localized, style: .plain, target: self, action: #selector(scanNearDevice))
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "WiFi".localized
        navigationItem.rightBarButtonItem = rightItem
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints {
            $0.edges.equalTo(self.view.usnp.edges)
        }
        
        /// ios 14.0+需要发送一条广播出发弹窗本地网络的弹窗
        if #available(iOS 14, *) {
            PTDispatcher.share()?.sendBroadcastMessages()
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //防止切换连接的时候会走断开连接的回调
        PTDispatcher.share()?.unconnectBlock = nil
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        PTDispatcher.share()?.stopScanAtLAN()
    }

    @objc private func scanNearDevice() {
        SVProgressHUD.show()
        PTDispatcher.share()?.scanDevice(atLAN: 5)
        
        PTDispatcher.share()?.whenFindAllBluetooth({ [weak self] devices in
            guard let self = self else { return }
            guard let temp = devices as? [PTPrinter] else { return  }
            if temp.count == 0 {
                SVProgressHUD.showError(withStatus: "Device not found".localized)
                return
            }
            SVProgressHUD.dismiss()
            self.dataSources = temp
            self.tableView.reloadData()
        })
        
    }
}

extension PDWiFiScanViewController : UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSources.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 = dataSources[indexPath.row].name
        cell?.detailTextLabel?.text = dataSources[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 pt = dataSources[indexPath.row]
        SVProgressHUD.show(withStatus: "Connecting, pls. wait".localized)
        PTDispatcher.share()?.connect(pt)
        
        PTDispatcher.share()?.whenConnectSuccess { [weak self] in
            guard let self = self else { return }
            SVProgressHUD.dismiss()
            self.showAlert(title: "Select paper size".localized, buttonTitles: ["2\" (384dots)", "3\" (576dots)", "3\" (640dots)", "4\" (832dots)","8\" (2360dots)", "12\" (3540dots)"], handler: { (selectedButtonIndex) in
                self.didSelectPaperSize(buttonIndex: selectedButtonIndex)
            })
        }
        
        PTDispatcher.share()?.whenConnectFailureWithErrorBlock { (error) in
            var errorStr: String?
            switch error {
            case .streamTimeout:
                errorStr = "Connection timeout".localized
            case .streamEmpty:
                errorStr = "Connection Error".localized
                case .streamOccured:
                    errorStr = "Connection Error".localized
            default:
                break
            }
            if let temp = errorStr {
                SVProgressHUD.showError(withStatus: temp)
            }
        }
        
        PTDispatcher.share()?.whenReceiveData({ (_) in
            
        })
    }
}
