//
//  ConnectViewController.swift
//  wifiprint
//
//  Created by woosimsystems on 2021/05/18.
//  Copyright © 2021 Woosim Systems. All rights reserved.
//

import UIKit

class ConnectViewController: UIViewController {

    @IBOutlet weak var hostIpTextField: UITextField!
    @IBOutlet weak var portTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
    }
    
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }
    
    @IBAction func connectSocket(_ sender: Any) {
        let ip = hostIpTextField.text ?? " "
        let port = Int(portTextField.text ?? "0") ?? 0
        let socket = SocketController()
        if socket.connect(host: ip, port: port) {
            guard let nvc = self.presentingViewController as? UINavigationController else { return }
            guard let vc = nvc.topViewController as? ViewController else { return }
            vc.socket = socket
            dismiss(animated: true, completion: nil)
        } else {
            let alert = UIAlertController(title: "Error",
                                          message: "Connection failed.",
                                          preferredStyle: UIAlertController.Style.alert)
            let cancelAction = UIAlertAction(title: "Close", style: .default, handler: nil)
            alert.addAction(cancelAction)
            present(alert, animated: true, completion: nil)
        }
    }
    
    @IBAction func closeView(_ sender: Any) {
        dismiss(animated: true, completion: nil)
    }
}
