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

#import "ConnectViewController.h"
#import "SocketController.h"
#import "ViewController.h"

@interface ConnectViewController ()

@property (weak, nonatomic) IBOutlet UITextField *hostIpTextField;
@property (weak, nonatomic) IBOutlet UITextField *portTextField;

@end

@implementation ConnectViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (IBAction)connectSocket:(id)sender {
    NSString *ip = _hostIpTextField.text;
    NSInteger port = [_portTextField.text integerValue];
    SocketController *socket = [[SocketController alloc] init];
    if ([socket connect:ip withPort:port] == YES) {
        UINavigationController *nvc = (UINavigationController *)[self presentingViewController];
        ViewController *vc = (ViewController *)[nvc topViewController];
        vc.socket = socket;
        [self dismissViewControllerAnimated:YES completion:nil];
    } else {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                       message:@"Connection failed."
                                                                preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Close"
                                                               style:UIAlertActionStyleDefault
                                                             handler:nil];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }
}

- (IBAction)closeView:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

@end
