//
//  SlowWorkerViewController.m
//  SlowWorker
//
//  Created by Robert Górczyński on 11-07-20.
//

#import "SlowWorkerViewController.h"

@implementation SlowWorkerViewController

@synthesize startButton, resultsTextView; 
@synthesize spinner;

- (NSString *)fetchSomethingFromServer { 
    [NSThread sleepForTimeInterval:1]; 
    return @"Dzień dobry"; 
} 

- (NSString *)processData:(NSString *)data { 
    [NSThread sleepForTimeInterval:2]; 
    return [data uppercaseString]; 
} 

- (NSString *)calculateFirstResult:(NSString *)data { 
    [NSThread sleepForTimeInterval:3]; 
    return [NSString stringWithFormat:@"Liczba znaków: %d", 
            [data length]]; 
} 

- (NSString *)calculateSecondResult:(NSString *)data { 
    [NSThread sleepForTimeInterval:4]; 
    return [data stringByReplacingOccurrencesOfString:@"E" 
                                           withString:@"e"]; 
} 

- (IBAction)doWork:(id)sender {
    startButton.enabled = NO; 
    startButton.alpha = 0.5; 
    [spinner startAnimating]; 	
    NSDate *startTime = [NSDate date];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{ 
		NSString *fetchedData = [self fetchSomethingFromServer]; 
		NSString *processedData = [self processData:fetchedData]; 
        __block NSString *firstResult; 
        __block NSString *secondResult; 
        dispatch_group_t group = dispatch_group_create(); 
        dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 
            firstResult = [[self calculateFirstResult:processedData] retain]; 
        }); 
        dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{ 
            secondResult = [[self calculateSecondResult:processedData] retain]; 
        }); 
        dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{ 			
			NSString *resultsSummary = [NSString stringWithFormat: 
										@"Pierwszy: [%@]\nDrugi: [%@]", firstResult, 
										secondResult]; 
			dispatch_async(dispatch_get_main_queue(), ^{
				startButton.enabled = YES; 
				startButton.alpha = 1.0; 
				[spinner stopAnimating]; 			
				resultsTextView.text = resultsSummary;
			});
			NSDate *endTime = [NSDate date]; 
			NSLog(@"Ukończono w ciągu %f sekund",  
				  [endTime timeIntervalSinceDate:startTime]); 
            [firstResult release]; 
            [secondResult release];
		});
	});
} 

- (void)didReceiveMemoryWarning {
	// Jeżeli widok nie posiada widoku nadrzędnego, wówczas zostanie usunięty z pamięci.
    [super didReceiveMemoryWarning];
	
	// Usunięcie z pamięci wszelkich buforowanych danych, obrazów i innych zasobów, które obecnie nie są używane.
}

- (void)viewDidUnload {
	// Usunięcie wszystkich „przytrzymanych” podwidoków widoku głównego,
    // na przykład self.myOutlet = nil;
    self.startButton = nil; 
    self.resultsTextView = nil;
    self.spinner = nil; 
    [super viewDidUnload]; 	
}


- (void)dealloc {
    [startButton release]; 
    [resultsTextView release]; 
    [spinner release]; 
    [super dealloc];
}

@end
