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

import UIKit
import PrinterSDK
import SVProgressHUD
import SwifterBaseKit

class PDConfigWiFiParaController: PDBaseViewController {

    @IBOutlet weak var ipTF: UILabel!
    @IBOutlet weak var maskTF: UILabel!
    @IBOutlet weak var gatewayTF: UILabel!
    @IBOutlet weak var dhcpSegment: UISegmentedControl!
    @IBOutlet weak var maskLb: UILabel!
    @IBOutlet weak var gatewayLb: UILabel!
    @IBOutlet weak var configButton: UIButton!
        
    var infoTimer: Timer?
    
    private lazy var rightItem: UIBarButtonItem = {
        return UIBarButtonItem(title: "Read".localized, style: .plain, target: self, action: #selector(readWiFiParametersInfo))
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Configure network parameters".localized
        navigationItem.rightBarButtonItem = rightItem
        view.backgroundColor = UIColor.white
    }
    
    override func configUI() {
        maskLb.text = "Subnet mask".localized
        gatewayLb.text = "Gateway".localized
        
        ipTF.cornerRadius = 5
        ipTF.textColor = .white
        ipTF.backgroundColor = UIColor.theme
        maskTF.cornerRadius = 5
        maskTF.textColor = .white
        maskTF.backgroundColor = UIColor.theme
        gatewayTF.cornerRadius = 5
        gatewayTF.textColor = .white
        gatewayTF.backgroundColor = UIColor.theme
        
        dhcpSegment.setTitle("Close".localized, forSegmentAt: 0)
        dhcpSegment.setTitle("Open".localized, forSegmentAt: 1)
        dhcpSegment.selectedSegmentIndex = -1
        if #available(iOS 13, *) {
            dhcpSegment.selectedSegmentTintColor = UIColor.theme
        }else {
            dhcpSegment.tintColor = UIColor.theme
        }
        dhcpSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.black], for: UIControl.State.normal)
        dhcpSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.white], for: UIControl.State.selected)
        
        gatewayTF.text = "255.255.255.0"
        
        configButton.cornerRadius = 5
        configButton.setTitle("Set network parameters".localized, for: .normal)
        configButton.backgroundColor = UIColor.theme
        configButton.setTitleColor(UIColor.white, for: .normal)
    }
        
    @IBAction func didSelectIPAdressAction(_ sender: Any) {
        guard let temp = kAppWindow.rootViewController else { return }
        let pickerVC = PDSelectPickerViewController()
        pickerVC.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        pickerVC.view.frame = temp.view.bounds
        pickerVC.selectedIP = ipTF.text
        temp.addChild(pickerVC)
        temp.view.addSubview(pickerVC.view)
        pickerVC.refreshIP()
        pickerVC.selectIPClosure = {[weak self](ip1,ip2,ip3,ip4) in
            guard let self = self else { return }
            self.ipTF.text = "\(ip1).\(ip2).\(ip3).\(ip4)"
        }
    }
    
    
    @IBAction func didSelectMaskAction(_ sender: Any) {
        guard let temp = kAppWindow.rootViewController else { return }
        let pickerVC = PDSelectPickerViewController()
        pickerVC.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        pickerVC.view.frame = temp.view.bounds
        pickerVC.selectedIP = maskTF.text
        temp.addChild(pickerVC)
        temp.view.addSubview(pickerVC.view)
        pickerVC.refreshIP()
        pickerVC.selectIPClosure = {[weak self](ip1,ip2,ip3,ip4) in
            guard let self = self else { return }
            self.maskTF.text = "\(ip1).\(ip2).\(ip3).\(ip4)"
        }
    }
    
    
    @IBAction func didSelectGatewayAction(_ sender: Any) {
        guard let temp = kAppWindow.rootViewController else { return }
        let pickerVC = PDSelectPickerViewController()
        pickerVC.view.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        pickerVC.view.frame = temp.view.bounds
        pickerVC.selectedIP = gatewayTF.text
        temp.addChild(pickerVC)
        temp.view.addSubview(pickerVC.view)
        pickerVC.refreshIP()
        pickerVC.selectIPClosure = {[weak self](ip1,ip2,ip3,ip4) in
            guard let self = self else { return }
            self.gatewayTF.text = "\(ip1).\(ip2).\(ip3).\(ip4)"
        }
    }
    
    @objc private func readWiFiParametersInfo() {
        
        readNetwordIpAddress()
    }
    
    private func readNetwordIpAddress() {
        let esc = PTCommandESC()
        esc.readPrinterWiFiIP()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            guard let tempData = data else { return }
            if tempData.count == 4 {
                self.ipTF.text = "\(tempData[3]).\(tempData[2]).\(tempData[1]).\(tempData[0])"
            }
            self.readNetworkMask()
        })
    }
    
    private func readNetworkMask() {
        let esc = PTCommandESC()
        esc.readPrinterWiFiSubnetMask()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            guard let tempData = data else { return }
            if tempData.count == 4 {
                self.maskTF.text = "\(tempData[3]).\(tempData[2]).\(tempData[1]).\(tempData[0])"
            }
            self.readNetworkGateway()
        })
    }
    
    private func readNetworkGateway() {
        let esc = PTCommandESC()
        esc.readPrinterWiFiGateway()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            guard let tempData = data else { return }
            if tempData.count == 4 {
                self.gatewayTF.text = "\(tempData[3]).\(tempData[2]).\(tempData[1]).\(tempData[0])"
            }
            self.readNetworkDhcpStatus()
        })
    }
    
    private func readNetworkDhcpStatus() {
        let esc = PTCommandESC()
        esc.readPrinterWiFiDhcpStatus()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            guard let tempData = data else { return }
            if let state = tempData.read(to: UInt8.self) {
                self.dhcpSegment.selectedSegmentIndex = Int(state)
            }
        })
    }
    
    
    @IBAction func didStartConfigAction(_ sender: Any) {
        
        guard let ip = ipTF.text, let mask = maskTF.text, let gateway = gatewayTF.text else {
            SVProgressHUD.showInfo(withStatus: "Incomplete content".localized)
            return
        }
        if ip.isEmpty || mask.isEmpty || gateway.isEmpty {
            SVProgressHUD.showInfo(withStatus: "Incomplete content".localized)
            return
        }
        SVProgressHUD.show()
        
        infoTimer = Timer.after(3) {
            SVProgressHUD.showError(withStatus: "Setup failed".localized)
        }
        
        setPrinterDHCP()
    }
    
    private func setPrinterDHCP() {
        var resultData = Data()
        let esc = PTCommandESC()
        esc.setPrinterWiFiDhcpStatus(dhcpSegment.selectedSegmentIndex)
        esc.saveWiFiParametersSetting()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            self.infoTimer?.invalidate()
            self.infoTimer = nil
            guard let tempData = data else { return }
            resultData.append(tempData)
            if resultData.count == 4 {
                if resultData[2] == 0 || resultData[2] == 4 {
                    self.setPrinterIpAddress()
                }else {
                    SVProgressHUD.showError(withStatus: "Setup failed".localized)
                }
            }
        })
    }
    
    private func setPrinterIpAddress() {
        var resultData = Data()
        let esc = PTCommandESC()
        esc.setPrinterWiFiIPAddress(self.ipTF.text!)
        esc.saveWiFiParametersSetting()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            self.infoTimer?.invalidate()
            self.infoTimer = nil
            guard let tempData = data else { return }
            resultData.append(tempData)
            if resultData.count == 4 {
                if resultData[2] == 0 || resultData[2] == 4 {
                    self.setPrinterMask()
                }else {
                    SVProgressHUD.showError(withStatus: "Setup failed".localized)
                }
            }
        })
    }
    
    private func setPrinterMask() {
        var resultData = Data()
        let esc = PTCommandESC()
        esc.setPrinterWiFiSubnetMask(self.maskTF.text!)
        esc.saveWiFiParametersSetting()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            self.infoTimer?.invalidate()
            self.infoTimer = nil
            guard let tempData = data else { return }
            resultData.append(tempData)
            if resultData.count == 4 {
                if resultData[2] == 0 || resultData[2] == 4 {
                    self.setPrintergateway()
                }else {
                    SVProgressHUD.showError(withStatus: "Setup failed".localized)
                }
            }
        })
    }
    
    private func setPrintergateway() {
        var resultData = Data()
        let esc = PTCommandESC()
        esc.setPrinterWiFiGateway(self.gatewayTF.text!)
        esc.saveWiFiParametersSetting()
        PTDispatcher.share()?.send(esc.getCommandData())
        PTDispatcher.share()?.whenReceiveData({ [weak self](data) in
            guard let self = self else { return }
            self.infoTimer?.invalidate()
            self.infoTimer = nil
            guard let tempData = data else { return }
            resultData.append(tempData)
            if resultData.count == 4 {
                if resultData[2] == 0 || resultData[2] == 4 {
                    SVProgressHUD.showSuccess(withStatus: "The setting is successful, please restart the printer and use it again".localized)
                }else {
                    SVProgressHUD.showError(withStatus: "Setup failed".localized)
                }
            }
        })
    }
    
    

}
