//
//  AppDelegate.m
//  NG911
//
//  Created by Mason Silber on 9/9/11.
//  Copyright (c) 2011 Columbia University. All rights reserved.
//

#import "AppDelegate.h"
#import "Reachability.h"
#import "IMViewController.h"
#import "RTTViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;
@synthesize loading;
@synthesize textSize;
@synthesize messageType;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [loading release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    if(![AppDelegate connectedToInternet])
    {
        UIAlertView *noInternetAlert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" 
                                                                  message:@"Your device has no available internet connection. Please connect to the internet and relaunch app" 
                                                                 delegate:self 
                                                        cancelButtonTitle:@"Exit" 
                                                        otherButtonTitles:nil, nil];
        [noInternetAlert setTag:0];
        [noInternetAlert show];
        [noInternetAlert release];
        return NO;
    }

    loading = [[LoadingViewController alloc] initWithNibName:nil bundle:nil];
    [[loading view] setFrame:CGRectMake(85, 100, 150, 180)];
    
    if (![[NSUserDefaults standardUserDefaults] objectForKey:@"textSize"])  {
        
        NSString  *mainBundlePath = [[NSBundle mainBundle] bundlePath];
        NSString  *settingsPropertyListPath = [mainBundlePath
                                               stringByAppendingPathComponent:@"Settings.bundle/Root.plist"];
        
        NSDictionary *settingsPropertyList = [NSDictionary 
                                              dictionaryWithContentsOfFile:settingsPropertyListPath];
        
        NSMutableArray      *preferenceArray = [settingsPropertyList objectForKey:@"PreferenceSpecifiers"];
        NSMutableDictionary *registerableDictionary = [NSMutableDictionary dictionary];
        
        for (int i = 0; i < [preferenceArray count]; i++)  { 
            NSString  *key = [[preferenceArray objectAtIndex:i] objectForKey:@"Key"];
            
            if (key)  {
                id value = [[preferenceArray objectAtIndex:i] objectForKey:@"DefaultValue"];
                
                if(value)
                {
                    [registerableDictionary setObject:value forKey:key];
                }
            }
        }
        
        [[NSUserDefaults standardUserDefaults] registerDefaults:registerableDictionary]; 
        [[NSUserDefaults standardUserDefaults] synchronize]; 
    } 
    
    textSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"textSize"];
    messageType = [[NSUserDefaults standardUserDefaults] stringForKey:@"messageType"];
    
    if(!messageType || [messageType length] == 0)
    {
        UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Warning"
                                                           message:@"This is an emergency communication tool. Are you sure you want to continue?"
                                                          delegate:self
                                                 cancelButtonTitle:@"Exit"
                                                 otherButtonTitles:@"Realtime Text",@"Instant Message", nil];
        [warningAlert setTag:1];
        [warningAlert show];
        [warningAlert release];
    }
    else
    {
        UIAlertView *warningAlert = [[UIAlertView alloc] initWithTitle:@"Warning"
                                                               message:@"This is an emergency communication tool. Are you sure you want to continue?"
                                                              delegate:self
                                                     cancelButtonTitle:@"Exit" 
                                                     otherButtonTitles:@"Yes", nil];
        [warningAlert setTag:3];
        [warningAlert show];
        [warningAlert release];
    }
    return YES;
}

-(void)continueLoadingAppWithType:(NSString *)type
{    
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    
    if([type isEqualToString:@"IM"])
    {
        // Override point for customization after application launch.
        self.viewController = [[[IMViewController alloc] initWithNibName:nil bundle:nil] autorelease];
        navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
        [[self window] setRootViewController:navigationController];
        [[[[navigationController viewControllers] objectAtIndex:0] view] addSubview:[loading view]];
        [self.window makeKeyAndVisible];
    }
    else if([type isEqualToString:@"RTT"])
    {
        self.viewController = [[[RTTViewController alloc] initWithNibName:nil bundle:nil] autorelease];
        navigationController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
        [[self window] setRootViewController:navigationController];
        [[[[navigationController viewControllers] objectAtIndex:0] view] addSubview:[loading view]];
        [self.window makeKeyAndVisible];
    }
    else
    {
        UIAlertView *criticalErrorAlert = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                     message:@"Main view did not load correctly. Please restart app."
                                                                    delegate:self
                                                           cancelButtonTitle:@"Exit" 
                                                           otherButtonTitles:nil, nil];
        [criticalErrorAlert setTag:2];
        [criticalErrorAlert show];
        [criticalErrorAlert release];
    }   
}

+(BOOL)connectedToInternet
{
    Reachability *internetTester = [Reachability reachabilityForInternetConnection];
    NetworkStatus internetStatus = [internetTester currentReachabilityStatus];
    
    return internetStatus != NotReachable;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    //For testing purposes
    exit(1);
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    /*
     Called when the application is about to terminate.
     Save data if appropriate.
     See also applicationDidEnterBackground:.
     */
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if([alertView tag] == 0)
    {
        if(buttonIndex == [alertView cancelButtonIndex])
        {
            NSLog(@"No internet");
            exit(1);
        }
    }
    else if([alertView tag] == 1)
    {
        if(buttonIndex == [alertView cancelButtonIndex])
        {
            exit(1);
        }
        else if(buttonIndex == 1)
        {
            [alertView dismissWithClickedButtonIndex:1 animated:YES];
            [[NSUserDefaults standardUserDefaults] setObject:@"RTT" forKey:@"messageType"];
            [self continueLoadingAppWithType:@"RTT"];
        }
        else
        {
            [alertView dismissWithClickedButtonIndex:2 animated:YES];
            [[NSUserDefaults standardUserDefaults] setObject:@"IM" forKey:@"messageType"];
            [self continueLoadingAppWithType:@"IM"];
        }
    }
    else if([alertView tag] == 2)
    {
        NSLog(@"Main view failed");
        exit(1);
    }
    else if([alertView tag] == 3)
    {
        if(buttonIndex == [alertView cancelButtonIndex])
        {
            exit(1);
        }
        else
        {
            [alertView dismissWithClickedButtonIndex:1 animated:YES];
            [self continueLoadingAppWithType:messageType];
        }
    }
}
@end
