//
//  AppDelegate.m
//  Allzic
//
//  Created by Alia Bourouis on 03/02/14.
//  Copyright (c) 2014 Alia Bourouis. All rights reserved.
//

#import "AppDelegate.h"

/******* Set your tracking ID here *******/
static NSString *const kTrackingId = @"UA-26087717-28";
static NSString *const kAllowTracking = @"allowTracking";

@implementation AppDelegate

@synthesize screenBounds,systemVersion/*,tracker*/,dataController,introVC,allzicVC,playerVC,categoriesVC,categoriesRadiosVC,countryListVC,departmentListVC,cityRadiosVC,exploreVC,lastRadiosVC,aroundMeRadioVC,randomRadioVC,topRadioVC,favoriteVC,plusVC,searchVC,oldVC,isSearching;


///////////////////////////////////////
//   Notifications Push Apps Panel   //
///////////////////////////////////////

#pragma mark - PUSH

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    [[AppsPanel sharedInstance] registerWithDeviceToken:deviceToken andApp:application];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    [[AppsPanel sharedInstance] didReceiveRemoteNotificationAPPSPANEL:userInfo];
}

///////////////////////////////////////




- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // Override point for customization after application launch.
    
    [[AppsPanel sharedInstance] checkForNotificationsAtLaunching:launchOptions];
    [AppsPanel setAPControllerLogType:APLogTypeNone];
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:NO];
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
    if(![[AVAudioSession sharedInstance] setActive:YES error:nil])
    {
        NSLog(@"Failed to set up a session.");
    }
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    screenBounds = [[UIScreen mainScreen] bounds];
    systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    self.window = [[UIWindow alloc] initWithFrame:screenBounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    
    
    
    NSDictionary *appDefaults = @{kAllowTracking: @(YES)};
    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];
    // User must be able to opt out of tracking
    [GAI sharedInstance].optOut = ![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];
    // Initialize Google Analytics with a 120-second dispatch interval. There is a
    // tradeoff between battery usage and timely dispatch.
    [GAI sharedInstance].dispatchInterval = 10;
    [GAI sharedInstance].trackUncaughtExceptions = YES;
    self.tracker = [[GAI sharedInstance] trackerWithName:@"Allzic Radio" trackingId:kTrackingId];
    
    
    
    
    
    introVC = [[IntroViewController alloc] init];
    
    allzicVC = [[AllzicViewController alloc] init];
    [allzicVC setNavigationTitle:@""];
    [allzicVC setCurrentTabIndex:0];
    
    playerVC = [[PlayerViewController alloc] init];
    [playerVC setCurrentTabIndex:0];
    
    categoriesVC = [[CategoriesViewController alloc] init];
    [categoriesVC setNavigationTitle:@"Catégories"];
    [categoriesVC setCurrentTabIndex:1];
    
    categoriesRadiosVC = [[CategoriesRadiosViewController alloc] init];
    [categoriesRadiosVC setNavigationTitle:@"Catégories"];
    
    countryListVC = [[CountryListViewController alloc] init];
    [countryListVC setNavigationTitle:@"Liste des pays"];
    
    departmentListVC = [[DepartmentListViewController alloc] init];
    [departmentListVC setNavigationTitle:@"Liste des départements"];
    [departmentListVC setCurrentTabIndex:1];
    
    cityRadiosVC = [[CityRadiosViewController alloc] init];
    [cityRadiosVC setNavigationTitle:@"Liste des villes"];
    [cityRadiosVC setCurrentTabIndex:2];
    
    exploreVC = [[ExploreViewController alloc] init];
    [exploreVC setNavigationTitle:@"Explorer"];
    [exploreVC setCurrentTabIndex:2];
    
    lastRadiosVC = [[LastRadiosViewController alloc] init];
    [lastRadiosVC setNavigationTitle:@"Écoutes récentes"];
    [lastRadiosVC setCurrentTabIndex:2];
    
    aroundMeRadioVC = [[AroundMeRadioViewController alloc] init];
    [aroundMeRadioVC setNavigationTitle:@"Autour de moi"];
    [aroundMeRadioVC setCurrentTabIndex:2];
    
    randomRadioVC = [[RandomRadioViewController alloc] init];
    [randomRadioVC setNavigationTitle:@"Découvrir"];
    [randomRadioVC setCurrentTabIndex:2];
    
    topRadioVC = [[TopRadioViewController alloc] init];
    [topRadioVC setNavigationTitle:@"Top 10 des radios"];
    [topRadioVC setCurrentTabIndex:2];
    
    favoriteVC = [[FavoriteViewController alloc] init];
    [favoriteVC setNavigationTitle:@"Favoris"];
    [favoriteVC setCurrentTabIndex:3];
    
    plusVC = [[PlusViewController alloc] init];
    [plusVC setNavigationTitle:@"Plus"];
    [plusVC setCurrentTabIndex:4];
    
    searchVC = [[SearchViewController alloc] init];
    [searchVC setNavigationTitle:@"Recherche"];
    
    dataController = [DataController sharedInstance];
    
    NSString *isIntroAlreadyShown = [self.dataController.userPreferences objectForKey:@"isIntroAlreadyShown"];
    [self.window setRootViewController:introVC];
    [self.introVC launchAppButtonPressed];
    
    /*
    if (isIntroAlreadyShown == nil || isIntroAlreadyShown.length == 0) {
        [self.introVC displayTutorial];
    } else {
        [self.introVC launchAppButtonPressed];
    }
    */
    
    [self.window makeKeyAndVisible];
    return YES;
}

- (void)selectTab:(UIButton *)sender {
    
    
    switch (sender.tag) {
        //onglet Allzic
        case 0: {
            if (self.allzicVC.dataArray == nil || self.allzicVC.dataArray.count == 0) {
                [self.dataController parseAllzicRadios];
            }
            [self.window setRootViewController:allzicVC];
        }
            break;
        //onglet Categories
        case 1: {
            [self.window setRootViewController:categoriesVC];
        }
            break;
        //onglet Decouvrir
        case 2: {
            [self.window setRootViewController:exploreVC];
        }
            break;
        //onglet Favoris
        case 3: {
            [self.favoriteVC refreshTableWithData:[NSArray arrayWithObjects:self.dataController.favoriteCategoryArray,self.dataController.favoriteRadioArray, nil]];
            [self.window setRootViewController:favoriteVC];
        }
            break;
        //onglet Plus
        case 4: {
            [self.window setRootViewController:plusVC];
        }
            break;
        default:
            break;
    }
}

- (void)likeRadio {
    
    [self.dataController addFavoriteRadio:[self.dataController.currentRadioArray objectAtIndex:self.dataController.currentRadioIndex]];
    [self.playerVC refreshRadioWithFavorite:YES];
    [self.allzicVC refreshNowPlayingViewWithFavorite:YES];
    [self.categoriesVC refreshNowPlayingViewWithFavorite:YES];
    [self.categoriesRadiosVC refreshNowPlayingViewWithFavorite:YES];
    [self.exploreVC refreshNowPlayingViewWithFavorite:YES];
    [self.favoriteVC refreshNowPlayingViewWithFavorite:YES];
    
    [self.favoriteVC refreshTableWithData:[NSArray arrayWithObjects:self.dataController.favoriteCategoryArray,self.dataController.favoriteRadioArray, nil]];
}

- (void)unlikeRadio {
    
    [self.dataController removeFavoriteRadioWithId:[[self.dataController.currentRadioArray objectAtIndex:self.dataController.currentRadioIndex] objectForKey:@"id"]];
    [self.playerVC refreshRadioWithFavorite:NO];
    [self.allzicVC refreshNowPlayingViewWithFavorite:NO];
    [self.categoriesVC refreshNowPlayingViewWithFavorite:NO];
    [self.categoriesRadiosVC refreshNowPlayingViewWithFavorite:NO];
    [self.exploreVC refreshNowPlayingViewWithFavorite:NO];
    [self.favoriteVC refreshNowPlayingViewWithFavorite:NO];
    
    [self.favoriteVC refreshTableWithData:[NSArray arrayWithObjects:self.dataController.favoriteCategoryArray,self.dataController.favoriteRadioArray, nil]];
}

- (void)likeCategory:(NSDictionary *)category {
    
    [self.dataController addFavoriteCategory:category];
    
    [self.favoriteVC refreshTableWithData:[NSArray arrayWithObjects:self.dataController.favoriteCategoryArray,self.dataController.favoriteRadioArray, nil]];
}

- (void)unlikeCategory:(NSDictionary *)category {
    
    [self.dataController removeFavoriteCategoryWithId:[category objectForKey:@"id"]];
    
    [self.favoriteVC refreshTableWithData:[NSArray arrayWithObjects:self.dataController.favoriteCategoryArray,self.dataController.favoriteRadioArray, nil]];
}

- (void)refreshAllzicVC {
    
    [self.allzicVC refreshTableWithData:dataController.allzicRadiosParser.radioArray];
}

- (void)refreshCategoriesVC {
    
    [self.categoriesVC refreshTableWithData:dataController.categoriesParser.radioArray];
}

- (void)refreshCategoriesRadiosVC {
    
    [self.categoriesRadiosVC refreshTableWithData:dataController.categoriesRadiosParser.radioArray];
}

- (void)refreshCountryListVC {
    
    [self.countryListVC refreshTableWithData:dataController.countryRadiosParser.radioArray];
}

- (void)refreshDepartmentListVC {
    
    [self.departmentListVC refreshTableWithData:dataController.departmentRadiosParser.radioArray];
}

- (void)refreshCityListVC {
    
    [self.categoriesRadiosVC refreshWithCityData:dataController.cityListParser.radioArray];
}

- (void)refreshCityRadiosVC {
    
    [self.cityRadiosVC refreshTableWithData:dataController.cityRadiosParser.radioArray];
}

- (void)refreshPlayerVC {
    
    [self.playerVC refreshPlaylistWithData:dataController.playlistParser.radioArray];
}

- (void)refreshAroudMeVC {
    
    [self.aroundMeRadioVC refreshTableWithData:dataController.aroundMeRadiosParser.radioArray];
}

- (void)refreshRandomRadioVC {
    
    [self.randomRadioVC refreshTableWithData:dataController.randomRadiosParser.radioArray];
}

- (void)refreshTopRadioVC {
    
    [self.topRadioVC refreshTableWithData:dataController.topRadiosParser.radioArray];
}

- (void)refreshSearchVC {
    
    [self.searchVC refreshTableWithData:dataController.searchParser.radioArray];
}

- (void)refreshPlayerAd {
    
    //affichage de la pub display au format charge dans le xml
    if (self.playerVC.isDisplayAdToPlay == YES) {
        if (self.dataController.adswizzParser.dataDictionary != nil && [self.dataController.adswizzParser.dataDictionary objectForKey:@"interstitial"] != nil && [[self.dataController.adswizzParser.dataDictionary objectForKey:@"interstitial"] isEqualToString:@"OK"]) {
            [self.playerVC loadAdInterstitial];
        } else if (self.dataController.adswizzParser.dataDictionary != nil && [self.dataController.adswizzParser.dataDictionary objectForKey:@"banner"] != nil && [[self.dataController.adswizzParser.dataDictionary objectForKey:@"banner"] isEqualToString:@"OK"]) {
            [self.playerVC loadAdBanner];
        }
    }
    if (self.playerVC.isAudioAdToPlay) {
        if (self.dataController.adswizzParser.dataDictionary != nil && [self.dataController.adswizzParser.dataDictionary objectForKey:@"audioMp3"] != nil && [[self.dataController.adswizzParser.dataDictionary objectForKey:@"audioMp3"] length] > 0) {
            [self.playerVC playAudioAd];
        }
        else {
            [self.playerVC playRadio];
        }
    }
}

- (void)refreshUpdateAndRating {
    
    int nbLaunch = 0;
    if ([dataController.userPreferences objectForKey:@"nbLaunch"] != nil) {
        nbLaunch = [[dataController.userPreferences objectForKey:@"nbLaunch"] intValue];
    }
    nbLaunch++;
    [dataController.userPreferences setValue:[NSNumber numberWithInt:nbLaunch] forKey:@"nbLaunch"];
    [dataController.userPreferences synchronize];
    
    NSDate *now = [NSDate date];
    NSDate *firstLaunchDate = [NSDate date];
    if ([dataController.userPreferences objectForKey:@"firstLaunchDate"] != nil) {
        firstLaunchDate = (NSDate *)[dataController.userPreferences objectForKey:@"firstLaunchDate"];
    } else {
        [dataController.userPreferences setValue:firstLaunchDate forKey:@"firstLaunchDate"];
        [dataController.userPreferences synchronize];
    }
    double timeInterval = [now timeIntervalSinceDate:firstLaunchDate];
    double threeDays = 60 * 60 * 24 * 3;
    
    NSString *isRatingDone = [dataController.userPreferences objectForKey:@"isRatingDone"];
    
    if (dataController.updateAndRatingParser.radioArray!= nil && dataController.updateAndRatingParser.radioArray.count > 0) {
        
        //affiche une alert pour aller noter l'application
        if ([[dataController.updateAndRatingParser.radioArray objectAtIndex:0] objectForKey:@"rating_url"] != nil &&
            [[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] objectForKey:@"rating_url"] length] > 0 &&
            isRatingDone == nil && (nbLaunch >= 7 || timeInterval >= threeDays)) {
            UIAlertView *alert = [[UIAlertView alloc] init];
            [alert setTag:1];
            [alert setTitle:@"Allzic Radio"];
            [alert setMessage:@"Vous aimez notre application ? Donnez-nous votre avis pour l'améliorer"];
            [alert addButtonWithTitle:@"Noter l'application"];
            [alert addButtonWithTitle:@"Me demander plus tard"];
            [alert addButtonWithTitle:@"Non merci"];
            [alert setDelegate:self];
            [alert show];
        }
        
        //affiche une alert pour mettre a jour l'application
        if ([[dataController.updateAndRatingParser.radioArray objectAtIndex:0] objectForKey:@"notice_version"] != nil &&
            [[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] objectForKey:@"notice_version"] length] > 0) {
            
            NSString *recentVersionStr = [[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_version"];
            CGFloat recentVersion = [recentVersionStr floatValue];
            NSString *currentVersionStr = [[[NSBundle mainBundle] infoDictionary] valueForKey:@"CFBundleVersion"];
            CGFloat currentVersion = [currentVersionStr floatValue];
            int recentNoticeIndex = [[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_id"] intValue];
            int currentNoticeIndex = 0;
            if ([dataController.userPreferences objectForKey:@"noticeIndex"] != nil) {
                currentNoticeIndex = [[dataController.userPreferences objectForKey:@"noticeIndex"] intValue];
            }
            if (recentVersion > currentVersion && recentNoticeIndex > currentNoticeIndex) {
                UIAlertView *alert = [[UIAlertView alloc] init];
                [alert setTag:2];
                [alert setTitle:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_title"]];
                [alert setMessage:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_text"]];
                [alert addButtonWithTitle:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_button_left_title"]];
                [alert addButtonWithTitle:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_button_right_title"]];
                [alert setDelegate:self];
                [alert show];
            }
        }
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    
    //alert pour noter l'appli
    if (alertView.tag == 1) {
        if (buttonIndex == 0) {
            NSLog(@"NOTER L'APPLI");
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"rating_url"]]];
            [dataController.userPreferences setValue:@"done" forKey:@"isRatingDone"];
            [dataController.userPreferences synchronize];
        } else if (buttonIndex == 1) {
            NSLog(@"ME DEMANDER PLUS TARD");
            [dataController.userPreferences setValue:[NSNumber numberWithInt:1] forKey:@"nbLaunch"];
            [dataController.userPreferences setValue:[NSDate date] forKey:@"firstLaunchDate"];
            [dataController.userPreferences synchronize];
        } else if (buttonIndex == 2) {
            NSLog(@"NON MERCI");
            [dataController.userPreferences setValue:@"done" forKey:@"isRatingDone"];
            [dataController.userPreferences synchronize];
        }
    }
    //alert pour mettre a jour l'appli
    else if (alertView.tag == 2) {
        if (buttonIndex == 0) {
            NSLog(@"ANNULER");
        } else if (buttonIndex == 1) {
            NSLog(@"METTRE A JOUR");
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_button_right_url"]]];
        }
        [dataController.userPreferences setValue:[NSNumber numberWithInt:[[[dataController.updateAndRatingParser.radioArray objectAtIndex:0] valueForKey:@"notice_id"] intValue]] forKey:@"noticeIndex"];
        [dataController.userPreferences synchronize];
    }
}

- (void)selectRadioWithData:(NSArray *)radios atIndex:(int)index {
    
    [self.window setRootViewController:self.playerVC];
    [dataController setCurrentRadioArray:radios andCurrentRadioIndex:index];
    [self.playerVC selectRadio:[radios objectAtIndex:index]];
    [self.lastRadiosVC refreshTableWithData:self.dataController.lastRadioArray];
}

- (void)selectCategoryWithData:(NSDictionary *)category {
    
    [self.window setRootViewController:self.categoriesRadiosVC];
    [categoriesRadiosVC refreshTableWithData:nil];
    [self.dataController parseRadiosWithCategory:[[category objectForKey:@"id"] intValue]];
    [self.categoriesRadiosVC setCategory:category];
}

- (void)selectCountryWithData:(NSDictionary *)country {
    
    [self.window setRootViewController:self.categoriesRadiosVC];
    [categoriesRadiosVC refreshTableWithData:nil];
    [self.dataController parseRadiosWithCountry:[country objectForKey:@"id"]];
    [self.categoriesRadiosVC setCategory:country];
}

- (void)selectDepartmentWithData:(NSDictionary *)department {
    
    [self.categoriesRadiosVC refreshTableWithData:nil];
    NSString *title = [department objectForKey:@"title"];
    NSArray *elements = [title componentsSeparatedByString:@" - "];
    if (elements != nil && elements.count > 0) {
        [self.dataController parseRadiosWithDepartment:[elements objectAtIndex:0]];
    }
    [self.categoriesRadiosVC setCategory:[NSDictionary dictionaryWithObject:title forKey:@"title"]];
    [self.window setRootViewController:self.categoriesRadiosVC];
    [self.categoriesRadiosVC setParentViewController:self.departmentListVC];
    [self.categoriesRadiosVC setCurrentTabIndex:1];
}

- (void)selectCityWithData:(NSString *)city {
    
    
}

- (void)shareOnFacebookWithData:(NSMutableDictionary *)sharingData {
    
    // This function will invoke the Feed Dialog to post to a user's Timeline and News Feed
    // It will attemnt to use the Facebook Native Share dialog
    // If that's not supported we'll fall back to the web based dialog.
    
    // Prepare the native share dialog parameters
    FBShareDialogParams *shareParams = [[FBShareDialogParams alloc] init];
    shareParams.link = [NSURL URLWithString:[sharingData objectForKey:@"link"]];
    shareParams.name = [sharingData objectForKey:@"name"];
    shareParams.caption= [sharingData objectForKey:@"caption"];
    shareParams.description = [sharingData objectForKey:@"description"];
    if ([sharingData objectForKey:@"picture"] != nil && [[sharingData objectForKey:@"picture"] length] > 0) {
        shareParams.picture= [NSURL URLWithString:[sharingData objectForKey:@"picture"]];
    }
    
    if ([FBDialogs canPresentShareDialogWithParams:shareParams]){
        
        [FBDialogs presentShareDialogWithParams:shareParams
                                    clientState:nil
                                        handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
                                            if(error) {
                                                NSLog(@"Error publishing story : %@",error);
                                            } else if (results[@"completionGesture"] && [results[@"completionGesture"] isEqualToString:@"cancel"]) {
                                                NSLog(@"User canceled story publishing.");
                                            } else {
                                                NSLog(@"Story published.");
                                            }
                                        }];
        
    }else {
        
        // Prepare the web dialog parameters
        NSDictionary *params = @{
                                 @"name" : shareParams.name,
                                 @"caption" : shareParams.caption,
                                 @"description" : shareParams.description,
                                 @"picture" : [sharingData objectForKey:@"picture"],
                                 @"link" : [sharingData objectForKey:@"link"]
                                 };
        
        // Invoke the dialog
        [FBWebDialogs presentFeedDialogModallyWithSession:nil
                                               parameters:params
                                                  handler:
         ^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
             if (error) {
                 NSLog(@"Error publishing story : %@",error);
             } else {
                 if (result == FBWebDialogResultDialogNotCompleted) {
                     NSLog(@"User canceled story publishing.");
                 } else {
                     NSLog(@"Story published.");
                 }
             }}];
    }
    
    
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    // attempt to extract a token from the url
    return [FBAppCall handleOpenURL:url
                  sourceApplication:sourceApplication
                    fallbackHandler:^(FBAppCall *call) {
                        NSLog(@"In fallback handler");
                    }];
}

- (void)shareOnTwitterWithData:(NSDictionary *)sharingData {
	
    //  Create an instance of the Tweet Sheet
    SLComposeViewController *tweetSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
    
    // Sets the completion handler.  Note that we don't know which thread the
    // block will be called on, so we need to ensure that any UI updates occur
    // on the main queue
    tweetSheet.completionHandler = ^(SLComposeViewControllerResult result) {
        switch(result) {
                //  This means the user cancelled without sending the Tweet
            case SLComposeViewControllerResultCancelled:
                NSLog(@"====== > > > CANCELLED");
                break;
                //  This means the user hit 'Send'
            case SLComposeViewControllerResultDone:
                NSLog(@"====== > > > DONE");
                break;
        }
        
        //  dismiss the Tweet Sheet
        //version iPad
        if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.window.rootViewController dismissViewControllerAnimated:NO completion:^{
                    NSLog(@"Tweet Sheet has been dismissed.");
                }];
            });
        }
        //version iPhone
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.window.rootViewController dismissViewControllerAnimated:NO completion:^{
                    NSLog(@"Tweet Sheet has been dismissed.");
                }];
            });
        }
    };
    
    NSString *stringToTweet = [sharingData objectForKey:@"description"];
    
    //  Set the initial body of the Tweet
    [tweetSheet setInitialText:stringToTweet];
    
    /*
     //  Adds an image to the Tweet
     if (![tweetSheet addImage:[UIImage imageNamed:@"default_thumb.png"]]) {
     NSLog(@"Unable to add the image!");
     }
     */
    
    //  Add an URL to the Tweet.  You can add multiple URLs.
    if (![tweetSheet addURL:[NSURL URLWithString:[sharingData  objectForKey:@"link"]]]){
        NSLog(@"Unable to add the URL!");
    }
    
    //  Presents the Tweet Sheet to the user
    //version iPad
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) {
        [self.window.rootViewController presentViewController:tweetSheet animated:NO completion:^{
            NSLog(@"Tweet sheet has been presented.");
        }];
    }
    //version iPhone
    else {
        [self.window.rootViewController presentViewController:tweetSheet animated:NO completion:^{
            NSLog(@"Tweet sheet has been presented.");
        }];
    }
    
}

- (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
{
    // 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.
    //[GAI sharedInstance].optOut = ![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];
    [self.dataController initParsers];
}

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

@end
