//
//  AppDelegate.m
//  iDing
//
//  Created by MacBook Pro on 28/01/13.
//  Copyright (c) 2013 Abusamy Ltd.. All rights reserved.
//

#import "AppDelegate.h"

#import "ViewController.h"
#import "SideMenuViewController.h"
#import "MFSideMenu.h"
#import "Reachability.h"

@implementation AppDelegate
@synthesize loggedUserName,BBBK,isFourcams,loggedPassword,isAutoUpdate,autoLogin,isPushNotif,isAlertsFirstUpdate,dToken,pullforRefresh,openPage,isAutoLogin;
- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    sleep(2);
    self.pullforRefresh = FALSE;
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
    {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil] autorelease];
       
        
    } else
    {
        self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController_iPad" bundle:nil] autorelease];
    }
    
    self.dToken = @"";
    self.openPage = 0;
    [self loadSettings ];
    iDNavCntrlr = [[UINavigationController alloc]initWithRootViewController:self.viewController];
   // self.window.rootViewController = self.viewController;
    
    self.window.rootViewController = iDNavCntrlr;
    [self.window makeKeyAndVisible];
   /* SideMenuViewController *sideMenuViewController = [[SideMenuViewController alloc] init];
    MenuOptions options = MenuButtonEnabled|BackButtonEnabled;
    // make sure to display the navigation controller before calling this
    [MFSideMenuManager configureWithNavigationController:iDNavCntrlr
                                      sideMenuController:sideMenuViewController
                                                menuSide:MenuLeftHandSide
                                                 options:options];*/
    
  /*  [[UIApplication sharedApplication]registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
    UIRemoteNotificationType enabledTypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
*/
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0)
    {
        [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge) categories:nil]];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        Boolean isPushEnabled = [[UIApplication sharedApplication] isRegisteredForRemoteNotifications ];
        NSLog(@"Notifications types: %@", isPushEnabled? @"Yes" : @"No");
    }
    else
    {
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
         (UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert)];
        UIRemoteNotificationType enabledTypes = [[UIApplication sharedApplication] enabledRemoteNotificationTypes];
        NSLog(@"Notifications types: %x", enabledTypes);
    }
    
     if(launchOptions!=nil)
    {
    NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];
    
    //Accept push notification when app is not open
    if (remoteNotif) {
        
        NSArray *keyArray = [launchOptions allKeys];
        if ([keyArray count] > 0) {
            id option = [launchOptions objectForKey:[keyArray objectAtIndex:0]];
            if ([option isKindOfClass:[NSURL class]]) {
                
                /*
                NSURL *url = (NSURL *)option;
                self.invokeString = [url absoluteString];
                NSLog(@"ContactInbox launchOptions = %@",url);
                 */
            }
        }

        self.openPage = -1;
    }
    }
    
    return YES;
}

-(BOOL)isInternetAvailable
{
    BOOL isAvailable = FALSE;
    Reachability* reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
    if(remoteHostStatus == NotReachable)
    {
        isAvailable = FALSE;
    }
    else if (remoteHostStatus == ReachableViaWiFi)
    {
        isAvailable = TRUE;
    }
    else if (remoteHostStatus == ReachableViaWWAN)
    {
        isAvailable = TRUE;
    }
    return isAvailable;
}

-(void)setBBBKID: (NSString*) bbbk
{
    BBBK = [bbbk copy];
    [self saveSettings];
}

-(NSString*) getDefautDeviceID
{
    if(BBBK!=NULL)
        if([BBBK length]>5)
            return BBBK;
    return @"N/A";
}

-(void)loadSettings
{
    self.isAutoUpdate           = FALSE;
    self.isPushNotif            = FALSE;
    self.isAlertsFirstUpdate    = FALSE;
    self.isAutoLogin            = FALSE;
    self.isFourcams           = FALSE;
    
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    self.isAutoUpdate          = [prefs boolForKey:@"isAutoUpdate"];
    self.isPushNotif           = [prefs boolForKey:@"isPushNotif"];
    self.isAutoLogin           = [prefs boolForKey:@"isAutoLogin"];
    self.isFourcams            = [prefs boolForKey:@"isFourcams"];
    self.isAlertsFirstUpdate   = [prefs boolForKey:@"isAlertsFirstUpdate"];
    
    self.loggedUserName     = [prefs objectForKey:@"loggedUserName"];
    self.loggedPassword     = [prefs objectForKey:@"loggedPassword"];
    self.BBBK = [prefs objectForKey:@"BBBK"];
    
    self.autoLogin          = [prefs boolForKey:@"autoLogin"];
    
}

-(void)saveSettings
{
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    [prefs setBool:autoLogin forKey:@"autoLogin"];
    [prefs setBool:isAutoUpdate forKey:@"isAutoUpdate"];
    [prefs setBool:isPushNotif forKey:@"isPushNotif"];
    [prefs setBool:isAutoLogin forKey:@"isAutoLogin"];
    [prefs setBool:isFourcams forKey:@"isFourcams"];
    
    [prefs setBool:isAlertsFirstUpdate forKey:@"isAlertsFirstUpdate"];
    
    [prefs setObject:loggedUserName forKey:@"loggedUserName"];
    [prefs setObject:loggedPassword forKey:@"loggedPassword"];
    [prefs setObject:BBBK forKey:@"BBBK"];
    
      [prefs synchronize];
}

- (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.
}

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)windowx
{
    if ([[self.window.rootViewController presentedViewController] isKindOfClass:[MPMoviePlayerViewController class]] ||
        [[self.window.rootViewController presentedViewController] isKindOfClass:NSClassFromString(@"MPInlineVideoFullscreenViewController")])
    {
        if ([self.window.rootViewController presentedViewController].isBeingDismissed)
        {
            return UIInterfaceOrientationMaskPortrait;
        }
        else
        {
            return UIInterfaceOrientationMaskAllButUpsideDown;
        }
    }
    
    return UIInterfaceOrientationMaskPortrait;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (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)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
   // NSLog(@"my token is %@",deviceToken);
    //NSString *token = [[NSString alloc]initWithData:deviceToken encoding:NSUTF8StringEncoding];
   // NSLog(@"the tokne is %@",token);
    
    /*NSString **/
    self.dToken = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    self.dToken = [dToken stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"Push tOken---%@",dToken);
    
   /* NSString *urlStr = [NSString stringWithFormat:@"https://%@/push_token", RINGFULDOMAIN];
    NSURL *url = [NSURL URLWithString:urlStr];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    
    [req setHTTPMethod:@"POST"] 
    [req setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-type"];
    NSMutableData *postBody = [NSMutableData data];
    [postBody appendData:[[NSString stringWithFormat:@"&token=%@",
                           dToken] dataUsingEncoding:NSUTF8StringEncoding]];
    
    [req setHTTPBody:postBody];
    [[NSURLConnection alloc] initWithRequest:req delegate:nil];*/
   
}
-(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    NSLog(@"failed to get token, error: %@",[error description]);

    dToken = @"";
}

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    NSDictionary *aps = [userInfo valueForKey:@"aps"];
    if(aps==nil)
        return;

    id alert = [aps objectForKey:@"alert"];
    if(alert==nil)
        return;

    NSString *alertValue = nil;
    if ([alert isKindOfClass:[NSString class]]) {
        alertValue = alert;
    } else if ([alert isKindOfClass:[NSDictionary class]]) {
        alertValue = [alert objectForKey:@"body"];
    }

   // NSString *alertValue = [[userInfo valueForKey:@"aps"]valueForKey:@"alert"];
    if(alertValue==nil)
        return;
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
    
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = alertValue;
    hud.margin = 10.f;
    hud.yOffset = 150.f;
    hud.removeFromSuperViewOnHide = YES;
    
    [hud hide:YES afterDelay:3];/*
    UIAlertView *pushalert = [[UIAlertView alloc]initWithTitle:@"Alert" message:alertValue delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [pushalert show];
    [pushalert release];*/
}

- (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier
  completionHandler:(void (^)())completionHandler
{
    BLog();
    /*
     Store the completion handler. The completion handler is invoked by the view controller's checkForAllDownloadsHavingCompleted method (if all the download tasks have been completed).
     */
	self.backgroundSessionCompletionHandler = completionHandler;
}


@end
