//
//  ViewController.m
//  k-observer-iphone
//
//  Created by vvv ооо on 26.08.12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "ConnectViewController.h"
#import "MainMenuViewController.h"
#import "AppDelegate.h"

extern AppDelegate* appDelegate;

@interface ConnectViewController ()

@end

@implementation ConnectViewController

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

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (IBAction)OnConnectPressed
{
    [appDelegate.spinner startAnimating];
    
    UITextField* address_tf = (UITextField*)[self.view viewWithTag:1];
    
    UITextField* port_tf = (UITextField*)[self.view viewWithTag:2];
    
    UIButton* btn_connect = (UIButton*)[self.view viewWithTag:3];
    
    [appDelegate.observerClient ConnectTo:address_tf.text onPort:port_tf.text];
    
    [btn_connect setUserInteractionEnabled:NO];

}


- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

-(void)UnlockConnectButton
{
    UIButton* btn_connect = (UIButton*)[self.view viewWithTag:3];
    [btn_connect setUserInteractionEnabled:YES];
    
}

-(void)OnConnectionClosed
{
    [self performSelectorOnMainThread:@selector(OnConnectionClosedImmediate) withObject:nil waitUntilDone:NO];
}

-(void)OnReceiveQuit
{
    [self performSelectorOnMainThread:@selector(OnReceiveQuitImmediate) withObject:nil waitUntilDone:NO];
}


-(void)OnReceiveQuitImmediate
{
    @autoreleasepool {
        
        
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Сервер недоступен"
                                                          message:@"Сервер недоступен"
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
        [message show];
        
        [appDelegate.spinner stopAnimating];
        [appDelegate.connectViewController UnlockConnectButton];
        [appDelegate.navController popToRootViewControllerAnimated:YES];
        
    }
}

-(void)OnConnectionClosedImmediate
{
    
    [appDelegate.spinner stopAnimating];
    [appDelegate.connectViewController UnlockConnectButton];
}




@end
