//
//  STAConfigTableViewCell.swift
//  Example
//
//  Created by ldc on 2024/1/27.
//

import UIKit
import PrinterSDK

class STAConfigTableViewCell: UITableViewCell {
    
    @IBOutlet weak var ssidTextField: UITextField!
    
    @IBOutlet weak var passwordTextField: UITextField!
    
    @IBOutlet weak var encriptionButton: UIButton!
    
    @IBOutlet weak var ipDHCPSegmentedControl: UISegmentedControl!
    
    @IBOutlet weak var ipTextField: UITextField!
    
    @IBOutlet weak var netMaskTextField: UITextField!
    
    @IBOutlet weak var gatewayTextField: UITextField!
    
    var config: S1WifiSTAConfig? {
        didSet {
            ssidTextField.text = config?.ssid
            passwordTextField.text = config?.password
            encriptionButton.setTitle(config?.encrytion.description ?? "选择加密方式", for: .normal)
            ipDHCPSegmentedControl.selectedSegmentIndex = config?.dhcpEnable ?? true ? 0 : 1
            ipTextField.text = config?.ip
            gatewayTextField.text = config?.gateway
        }
    }
    
    @IBAction func encriptionButtonAction(_ sender: UIButton) {
        
        let encryptions: [S1WiFiEncryption] = [
            .open,
            .wep,
            .wpa2_psk,
            .wpa_wpa2_psk,
            .wpa_psk,
            .wpa,
            .wpa2,
            .sae,
        ]
        self.viewController?.valuePick(encryptions, closure: { encryption in
            self.config?.encrytion = encryption
            self.encriptionButton.setTitle(encryption.description, for: .normal)
        })
    }
    
    @IBAction func segmentedControlValueChanged(_ sender: UISegmentedControl) {
        
        config?.dhcpEnable = sender.selectedSegmentIndex == 0
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
    }
    
}

extension STAConfigTableViewCell: UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        
        let value = textField.text ?? ""
        if textField == ssidTextField {
            config?.ssid = value
        }
        if textField == passwordTextField {
            config?.password = value
        }
        if textField == ipTextField {
            config?.ip = value
        }
        if textField == netMaskTextField {
            config?.mask = value
        }
        if textField == gatewayTextField {
            config?.gateway = value
        }
    }
}
