//
//  GMSSettingsTableViewController.m
//  GMS Sample
//
/*
 Version: 1.0
 
 Disclaimer: IMPORTANT:  This software is supplied to you by Genesys
 Telecommunications Laboratories Inc ("Genesys") in consideration of your agreement
 to the following terms, and your use, installation, modification or redistribution
 of this Genesys software constitutes acceptance of these terms.  If you do not
 agree with these terms, please do not use, install, modify or redistribute this
 Genesys software.
 
 In consideration of your agreement to abide by the following terms, and subject
 to these terms, Genesys grants you a personal, non-exclusive license, under
 Genesys's copyrights in this original Genesys software (the "Genesys Software"), to
 use, reproduce, modify and redistribute the Genesys Software, with or without
 modifications, in source and/or binary forms; provided that if you redistribute
 the Genesys Software in its entirety and without modifications, you must retain
 this notice and the following text and disclaimers in all such redistributions
 of the Genesys Software.
 
 Neither the name, trademarks, service marks or logos of Genesys Inc. may be used
 to endorse or promote products derived from the Genesys Software without specific
 prior written permission from Genesys.  Except as expressly stated in this notice,
 no other rights or licenses, express or implied, are granted by Genesys herein,
 including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Genesys Software may be
 incorporated.
 
 The Genesys Software is provided by Genesys on an "AS IS" basis.  GENESYS MAKES NO
 WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED
 WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 PURPOSE, REGARDING THE GENESYS SOFTWARE OR ITS USE AND OPERATION ALONE OR IN
 COMBINATION WITH YOUR PRODUCTS.
 
 IN NO EVENT SHALL GENESYS BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR
 DISTRIBUTION OF THE GENESYS SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF
 CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF
 GENESYS HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 
 Copyright (C) 2013 Genesys Inc. All Rights Reserved.
 */

#import "GMSSettingsTableViewController.h"
#import "GMSSettingsSelectViewController.h"
#import "GMSRequestViewController.h"
#import "GMSSettingsURLViewController.h"
#import "GMS_Sample-Swift.h"

@implementation GMSSettingsTableViewController {
    // instance variables declared in implementation context
    MKPointAnnotation *mapMarker;
    NSDateFormatter *dateFormat;
    GMSAppDelegate *appDelegate;
    GMSScreenSharing *screenSharing;
}

- (void)viewDidLoad
{
    appDelegate = (GMSAppDelegate*)[[UIApplication sharedApplication] delegate];
    [super viewDidLoad];
    [self updateServerURL];
    _callbackServiceTextField.text = appDelegate.callbackServiceName;
    _gmsAPNDebugSwitch.on = appDelegate.serverAPNDebug;
    
    _customerSegmentLabel.text = appDelegate.customerSegment;
    _themeLabel.text = appDelegate.themeFlavor;
    _contactTextField.text = appDelegate.contactNumber;
    
    _loginRequiredSwitch.on = appDelegate.loginRequired;
    
    _audioEnableSwitch.on = appDelegate.audioEnabled;
    _audioRecordSwitch.on = appDelegate.audioRecordEnabled;
    
    _provideCodeSwitch.on = appDelegate.provideCode;
    _clearChatSwitch.on = appDelegate.clearChatOnNewSession;
    
    NSString *langID = [[NSLocale preferredLanguages] objectAtIndex:0];
    NSString *lang = [[NSLocale currentLocale] displayNameForKey:NSLocaleLanguageCode value:langID];
    _languageLabel.text = lang;
    
    UIDevice *device = [UIDevice currentDevice];
    _deviceModelLabel.text = [NSString stringWithFormat:@"%@ %@", device.model, device.systemVersion];
    
    _apnTokenLabel.text = appDelegate.notifyToken;
    
    //Set up the date picker as the Date text field input view
    _dateTextField.inputView = _datePicker;
    _dateTextField.inputAccessoryView = _dateBar;
    
    dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MMM-YYYY HH:mm z"];
    
    _dateTextField.text = [dateFormat stringFromDate:appDelegate.date];

    
    //Set up the map view as the Location text field input view
    MKCoordinateRegion region;
    
    MKCoordinateSpan span;
    span.latitudeDelta  = 0.05; // Change these values to change the zoom
    span.longitudeDelta = 0.05;
    region.span = span;
    
    CLLocationCoordinate2D loc = [appDelegate.locationManager location].coordinate;
    
#if !(TARGET_IPHONE_SIMULATOR)
    //For unknown reasons that breaks Simulator Map View
    [_mapView setRegion:region animated:YES];
#endif
    [_mapView setCenterCoordinate:loc animated:YES];
    
    _locationTextField.inputView = _mapView;
    _locationTextField.inputAccessoryView = _mapBar;
    
    _locationTextField.text = [NSString stringWithFormat:@"Lat: %f, Long: %f", loc.latitude, loc.longitude];
    
    _versionLabel.text = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if (self.isMovingToParentViewController == NO)
    {
        // we're already on the navigation stack
        // another controller must have been popped off
        [self updateServerURL];
    }
    
    _screenSharingOnLabel.text = appDelegate.screenSharing != nil && appDelegate.screenSharing.isOn ? @"On": @"Off";
}

-(void) updateServerURL
{
    _serverURLLabel.text = [appDelegate.serverURLs objectAtIndex:appDelegate.serverURLSelected];
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if ([segue.identifier isEqualToString:@"customerSegment"]) {
        GMSSettingsSelectViewController *segmentVC = segue.destinationViewController;
        segmentVC.currentSelection = _customerSegmentLabel;
        segmentVC.updateBlock = ^(NSString *title){
            appDelegate.customerSegment = title;
        };
    }
    if ([segue.identifier isEqualToString:@"themeFlavor"]) {
        GMSSettingsSelectViewController *segmentVC = segue.destinationViewController;
        segmentVC.currentSelection = _themeLabel;
        segmentVC.updateBlock = ^(NSString *title){
            appDelegate.themeFlavor = title;
        };
    }

}


- (void)viewDidUnload {
    [self setDateTextField:nil];
    [self setDatePicker:nil];
    [self setContactTextField:nil];
    [self setLanguageLabel:nil];
    [self setLocationTextField:nil];
    [self setMapView:nil];
    [self setDeviceModelLabel:nil];
    [self setApnTokenLabel:nil];
    [self setDateBar:nil];
    [self setMapBar:nil];
    [self setCustomerSegmentLabel:nil];
    [self setThemeLabel:nil];
    mapMarker = nil;
    
    [self setGmsAPNDebugSwitch:nil];
    [self setLoginRequiredSwitch:nil];
    [self setAudioEnableSwitch:nil];
    [self setAudioRecordSwitch:nil];
    [self setProvideCodeSwitch:nil];
    [self setServerURLLabel:nil];
    [super viewDidUnload];
}

#pragma mark - GMSScreenSharingViewControllerDelegate delegate

-(void)updateScreenSharingState:(BOOL)state {
    
    self.screenSharingOnLabel.text = state ? @"On": @"Off";
}

#pragma mark - TextField delegates

- (void)updateFromTextField:(UITextField *)textField textToUpdate:(NSString *)txtStr {
    if (textField == _contactTextField) {
        appDelegate.contactNumber = textField.text;
    }
    else if (textField == _callbackServiceTextField) {
        appDelegate.callbackServiceName = textField.text;
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    [self updateFromTextField:textField textToUpdate:textField.text];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)replacementStr {
    NSString *proposedNewString = [[textField text] stringByReplacingCharactersInRange:range withString:replacementStr];
    [self updateFromTextField:textField textToUpdate:proposedNewString];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField {
    [self updateFromTextField:textField textToUpdate:@""];
    return YES;
}

//Dismiss keyboard when Return key is pressed
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

#pragma mark -
#pragma mark Date Actions

- (IBAction)dateCancel:(id)sender {
    _dateTextField.text = @"";
    appDelegate.date = nil;
    [_dateTextField resignFirstResponder];
}

- (IBAction)dateDone:(id)sender {
    //Set the selected date
    _dateTextField.text = [dateFormat stringFromDate:_datePicker.date];
    appDelegate.date = _datePicker.date;
    [_dateTextField resignFirstResponder];
}

- (IBAction)mapLocation:(UILongPressGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer.state != UIGestureRecognizerStateBegan)
        return;
    
    CGPoint touchPoint = [gestureRecognizer locationInView:_mapView];
    CLLocationCoordinate2D touchMapCoordinate = [_mapView convertPoint:touchPoint toCoordinateFromView:_mapView];
    [_mapView setCenterCoordinate:touchMapCoordinate];
    
    if (mapMarker == nil)
        mapMarker = [[MKPointAnnotation alloc] init];
    mapMarker.coordinate = touchMapCoordinate;
    mapMarker.title = @"Event Location";
    [_mapView addAnnotation:mapMarker];
}

- (IBAction)mapCancel:(id)sender {
    [_locationTextField resignFirstResponder];
    appDelegate.location = CLLocationCoordinate2DMake(0., 0.);
    _locationTextField.text = @"";
}

- (IBAction)mapDone:(id)sender {
    [_locationTextField resignFirstResponder];
    
    if (mapMarker == nil) {
        appDelegate.location = _mapView.userLocation.coordinate;
    }
    else {
        appDelegate.location = mapMarker.coordinate;
    }
    
    _locationTextField.text = [NSString stringWithFormat:@"Lat: %f, Long: %f", appDelegate.location.latitude, appDelegate.location.longitude];
}

- (IBAction)triggerPush:(id)sender {
    //Find GMSRequestViewController
    UITabBarController *tb = (UITabBarController *)appDelegate.window.rootViewController;
    for (id tbc in tb.viewControllers) {
        if ([tbc isKindOfClass:[UINavigationController class]] && [[tbc viewControllers][0] isKindOfClass:[GMSRequestViewController class]]) {
            [[tbc viewControllers][0] submitGMS:self];
            tb.selectedViewController = tbc;
        }
    }
}

- (IBAction)debugSwitch:(UISwitch *)sender {
    appDelegate.serverAPNDebug = sender.on;
}

- (IBAction)loginSwitch:(UISwitch *)sender {
    appDelegate.loginRequired = sender.on;
}

- (IBAction)audioSwitch:(UISwitch *)sender {
    appDelegate.audioEnabled = sender.on;
}

- (IBAction)recordSwitch:(UISwitch *)sender {
    appDelegate.audioRecordEnabled = sender.on;
    [[NSNotificationCenter defaultCenter] postNotificationName:kRecordingChangedNotification object:self];
}

- (IBAction)provideCodeSwitch:(UISwitch *)sender {
    appDelegate.provideCode = sender.on;
}

- (IBAction)clearChatSwitch:(UISwitch *)sender {
    appDelegate.clearChatOnNewSession = sender.on;
}

@end
