//
//  ReviewsAlert.m
//  PrayersReference
//
//  Created by Radu Cojocaru on 02.02.2010.
//  Copyright 2010 Surgeworks. All rights reserved.
//

#import "ReviewsAlert.h"


@implementation ReviewsAlert

+ (void)showReviewsAlert {
	ReviewsAlert *reviewsAlert = [[ReviewsAlert alloc] init];
	[reviewsAlert showReviewsAlert];
}

- (void)showReviewsAlert {
	// Set start date
	if ([[NSUserDefaults standardUserDefaults] objectForKey:@"reviewsAlertStartDate"] == NULL) {
		NSLog(@"no start date");
		[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"reviewsAlertStartDate"];
	}
	
	// Check if reviews alert was not banned ("Don't ask again")
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"reviewsAlertBanned"] == YES) {
		NSLog(@"reviews alert banned");
		return;
	}
	
	// Check if user already reviewed the app
	if ([[NSUserDefaults standardUserDefaults] boolForKey:@"userDidRate"] == YES) {
		NSLog(@"user did rate");
		return;
	}
	
	// Check if enough time has passed
	int daysToWait = (3600 * 24) * 10; // 10 days
	if ([[NSDate date] timeIntervalSinceDate:[[NSUserDefaults standardUserDefaults] objectForKey:@"reviewsAlertStartDate"]] < daysToWait) {
		NSLog(@"not enough time");
		return;
	}
	
	UIAlertView *alertView = [[[UIAlertView alloc] initWithTitle: @"Would you recommend this app to your friends?" 
														 message: @"If you find this App useful, please leave a positive review on the App Store to encourage other users to download it." 
														delegate: self 
											   cancelButtonTitle: @"Not now" 
											   otherButtonTitles: @"Go to the App Store", @"Don't ask again", nil] autorelease];
	[alertView show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 0) { // Cancel. Reset date
		[[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"reviewsAlertStartDate"];
	}
	else if (buttonIndex == 1) { // Go to the AppStore
		[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"userDidRate"];
		[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=307757516&pageNumber=0&sortOrdering=1&type=Purple+Software"]];
	}
	else if (buttonIndex == 2) { // Don't ask again
		[[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"reviewsAlertBanned"];
	}
}

@end
