//
//  GMSSettingsURLAddViewController.m
//  GMS Sample
//
//  Created by Arkady on 8/8/13.
//  Copyright (c) 2013 Genesys. All rights reserved.
//

#import "GMSSettingsURLAddViewController.h"
#import "GMSAppDelegate.h"

@interface GMSSettingsURLAddViewController ()
{
    GMSAppDelegate *_appDelegate;
}

@end

@implementation GMSSettingsURLAddViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    _appDelegate = (GMSAppDelegate*)[[UIApplication sharedApplication] delegate];
    
}

-(void) viewWillAppear:(BOOL)animated {
    if (_appDelegate.serverURLSelected == -1) {
        //We are adding new URL
        _hostTextField.text = @"host";
        _portTextField.text = @"8080";
        _applicationTextField.text = @"genesys";
        _httpsSwitch.on = NO;
    }
    else {
        // Editing an existing entry. Use an NSURL object to parse into components
        NSString *urlStr = [_appDelegate.serverURLs objectAtIndex:_editIndex];
        NSURL *url = [NSURL URLWithString:urlStr];
        _hostTextField.text = url.host;
        _portTextField.text = [url.port stringValue];
        _applicationTextField.text = [url.path substringFromIndex:1]; // Remove leading / from path
        _httpsSwitch.on = [url.scheme isEqualToString:@"https"] ? YES: NO;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // We intercept this to dismiss the keyboard when Done is tap
    [textField resignFirstResponder];
    return NO;
}

-(IBAction)doneButton:(id)sender {
    
    // Require the port field to be a numeric value
    int port = [_portTextField.text intValue];
    if (port <= 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid value for port"
                                                        message:@"Port must be an integer value"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    NSString *urlStr = [NSString stringWithFormat:@"%@://%@:%d/%@", _httpsSwitch.isOn ? @"https": @"http", _hostTextField.text, port, _applicationTextField.text];
    if (_appDelegate.serverURLSelected == -1) {
        //We are adding new URL
        [_appDelegate.serverURLs addObject:urlStr];
        _appDelegate.serverURLSelected = _appDelegate.serverURLs.count - 1;
    }
    else {
        // Updating an existing entry
        [_appDelegate.serverURLs setObject:urlStr atIndexedSubscript:_editIndex];
        _appDelegate.serverURLSelected = _appDelegate.serverURLSelected; // Need this to call setter to update GMSUtil base URL
    }
    [_parentTableView reloadData];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidUnload {
    [super viewDidUnload];
}
@end
