//
//  EthernetConfigViewController.swift
//  Example
//
//  Created by ldc on 2024/3/1.
//

import UIKit
import PrinterSDK
import SVProgressHUD

class EthernetConfigViewController: UIViewController {
    
    var config = S1EthernetConfig()
    let accessory: S1UdpLanTarget
    let configurator: S1UdpNetConfig
    
    init(configurator: S1UdpNetConfig, accessory: S1UdpLanTarget) {
        self.configurator = configurator
        self.accessory = accessory
        self.config.ip = "192.168.1.1"
        self.config.mask = "255.255.255.0"
        self.config.gateway = "192.168.1.1"
        if accessory.isEth {
            self.config.ip = accessory.ip
            self.config.gateway = accessory.gateway
            self.config.mask = accessory.mask
            self.config.dhcpEnable = accessory.dhcpEnable
        }
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    @IBOutlet weak var tableView: UITableView! {
        didSet {
            tableView.register(UINib(nibName: "EthernetConfigTableViewCell", bundle: nil), forCellReuseIdentifier: "iden")
        }
    }
    
    @IBAction func save(_ sender: UIButton) {
        
        view.endEditing(true)
        configurator.setEthernet(accessory, config: config) { error in
            if let error = error {
                self.show(S1ErrorDescription(error: error))
                return
            }
            self.show("保存成功")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        title = "以太网配置"
    }
}

extension EthernetConfigViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        
        return nil
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        
        return nil
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "iden", for: indexPath) as! EthernetConfigTableViewCell
        cell.config = config
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        tableView.deselectRow(at: indexPath, animated: true)
    }
}
