//
//  State_LabViewController.m
//  State Lab
//
//  Created by Robert Górczyński on 11-07-21.
//

#import "State_LabViewController.h"

@interface State_LabViewController () 
- (void)rotateLabelUp; 
- (void)rotateLabelDown; 
@end 

@implementation State_LabViewController
@synthesize label;
@synthesize smiley, smileyView; 
@synthesize segmentedControl; 


- (void)rotateLabelDown { 
    [UIView animateWithDuration:0.5
                          delay:0 
                        options:UIViewAnimationOptionAllowUserInteraction 
                     animations:^{ 
                         label.transform = CGAffineTransformMakeRotation(M_PI); 
                     } 
                     completion:^(BOOL finished){  
                         [self rotateLabelUp];  
                     }]; 
} 

- (void)rotateLabelUp { 
    [UIView animateWithDuration:0.5
                          delay:0 
                        options:UIViewAnimationOptionAllowUserInteraction 
                     animations:^{ 
                         label.transform = CGAffineTransformMakeRotation(0); 
                     } 
                     completion:^(BOOL finished){
						 if (animate) { 
							 [self rotateLabelDown];
						 }
                     }]; 
}

- (void)applicationWillResignActive { 
    NSLog(@"%@", NSStringFromSelector(_cmd)); 
    animate = NO; 
} 

- (void)applicationDidBecomeActive { 
    NSLog(@"%@", NSStringFromSelector(_cmd)); 
    animate = YES; 
    [self rotateLabelDown]; 
}

- (void)applicationDidEnterBackground { 
    NSLog(@"%@", NSStringFromSelector(_cmd));
    UIApplication *app = [UIApplication sharedApplication]; 
	
    __block UIBackgroundTaskIdentifier taskId; 
    taskId = [app beginBackgroundTaskWithExpirationHandler:^{ 
        NSLog(@"Zadanie działające w tle zabrało zbyt dużą ilość czasu i zostało zamknięte."); 
        [app endBackgroundTask:taskId]; 
    }]; 
	
    if (taskId == UIBackgroundTaskInvalid) { 
        NSLog(@"Nie udało się uruchomić zadania w tle!"); 
        return; 
    } 
	
    dispatch_async(dispatch_get_global_queue(0, 0), ^{         
        NSLog(@"Uruchomienie zadania w tle, pozostało %f sekund", 
              app.backgroundTimeRemaining); 		
    self.smiley = nil; 
    self.smileyView.image = nil; 
	
	NSInteger selectedIndex = self.segmentedControl.selectedSegmentIndex; 
    [[NSUserDefaults standardUserDefaults] setInteger:selectedIndex  
                                               forKey:@"selectedIndex"]; 	

    // Symulacja długo wykonywanej operacji.
    [NSThread sleepForTimeInterval:10];
        NSLog(@"Zakończenie zadania w tle, pozostało %f sekund", 
              app.backgroundTimeRemaining); 
        [app endBackgroundTask:taskId]; 
    }); 	
} 

- (void)applicationWillEnterForeground { 
    NSLog(@"%@", NSStringFromSelector(_cmd)); 
    NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" 
                                                           ofType:@"png"]; 
    self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; 
    self.smileyView.image = self.smiley; 
}

// Implementacja metody viewDidLoad pozwala na przeprowadzenie konfiguracji po wczytaniu widoku, zazwyczaj z pliku nib.
- (void)viewDidLoad {
    [super viewDidLoad];

	[[NSNotificationCenter defaultCenter] addObserver:self  
											 selector:@selector(applicationDidEnterBackground)  
												 name:UIApplicationDidEnterBackgroundNotification 
											   object:[UIApplication sharedApplication]]; 
	[[NSNotificationCenter defaultCenter] addObserver:self  
											 selector:@selector(applicationWillEnterForeground)  
												 name:UIApplicationWillEnterForegroundNotification 
											   object:[UIApplication sharedApplication]];	
    [[NSNotificationCenter defaultCenter] addObserver:self  
											 selector:@selector(applicationWillResignActive) 
												 name:UIApplicationWillResignActiveNotification 
											   object:[UIApplication sharedApplication]]; 
    [[NSNotificationCenter defaultCenter] addObserver:self  
											 selector:@selector(applicationDidBecomeActive) 
												 name:UIApplicationDidBecomeActiveNotification 
											   object:[UIApplication sharedApplication]];	
	
    CGRect bounds = self.view.bounds;
    CGRect labelFrame = CGRectMake(bounds.origin.x, CGRectGetMidY(bounds) - 50, 
                                   bounds.size.width, 100); 
    self.label = [[[UILabel alloc] initWithFrame:labelFrame] autorelease]; 
    label.font = [UIFont fontWithName:@"Helvetica" size:70]; 
    label.text = @"Helion!"; 
    label.textAlignment = UITextAlignmentCenter; 
    label.backgroundColor = [UIColor clearColor];
	
	// Wymiary pliku smiley.png to 84 x 84 
    CGRect smileyFrame = CGRectMake(CGRectGetMidX(bounds) - 42, 
                                    CGRectGetMidY(bounds)/2 - 42, 
                                    84, 84); 
    self.smileyView = [[[UIImageView alloc] initWithFrame:smileyFrame] autorelease]; 
    self.smileyView.contentMode = UIViewContentModeCenter; 
    NSString *smileyPath = [[NSBundle mainBundle] pathForResource:@"smiley" 
                                                           ofType:@"png"]; 
    self.smiley = [UIImage imageWithContentsOfFile:smileyPath]; 
    self.smileyView.image = self.smiley; 
	
	self.segmentedControl = [[[UISegmentedControl alloc] initWithItems: 
                              [NSArray arrayWithObjects: 
                               @"Jeden", @"Dwa", @"Trzy", @"Cztery", nil]] autorelease]; 
    self.segmentedControl.frame = CGRectMake(bounds.origin.x + 20,  
                                             CGRectGetMaxY(bounds) - 50, 
                                             bounds.size.width - 40, 30); 
	
    [self.view addSubview:segmentedControl]; 	
    [self.view addSubview:smileyView]; 	
    [self.view addSubview:label];

    NSNumber *indexNumber; 
    if (indexNumber = [[NSUserDefaults standardUserDefaults] 
                       objectForKey:@"selectedIndex"]) { 
        NSInteger selectedIndex = [indexNumber intValue]; 
        self.segmentedControl.selectedSegmentIndex = selectedIndex; 
    } 	
}

- (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.label = nil; 
    self.smiley = nil; 
    self.smileyView = nil; 
    self.segmentedControl = nil; 
    [super viewDidUnload]; 
}


- (void)dealloc {
    [label release]; 
    [smiley release]; 
    [smileyView release]; 
    [segmentedControl release]; 
    [super dealloc];
}

@end
