/*
iPhly: Radio Control on the iPhone

Copyright (C) 2010-2011 Ari Krupnik & Associates

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License V2
as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#import <SystemConfiguration/SCNetworkReachability.h>
#import <MediaPlayer/MPMoviePlayerController.h>
#import "TiltAndSwipeViewController.h"
#import "ModelConfigController.h"
#import "TiltAndSwipePadAir.h"
#import "TiltAndSwipePadCar.h"
#import "WebViewController.h"
#import "ModelListViewController.h"
#import "GlobalSettingsViewController.h"
#import "ac_audio.h"

NSString* CONFIGURE_MODEL = @"Configure this Model";
NSString* CHOOSE_MODEL = @"Model List";
NSString* GLOBAL_SETTINGS = @"Global Settings";
NSString* WATCH_VIDEO = @"Watch iPhly Video";
NSString* ORDER_HARDWARE = @"Buy iPhly Hardware";
NSString* ABOUT = @"About iPhly";

@implementation TiltAndSwipeViewController

@synthesize processor;
@synthesize configureBarButton;
@synthesize modelNameLabel;
@synthesize swipePad;
@synthesize airplaneModeWarning;
@synthesize configureSlider;
@synthesize configureSliderLabel;


int cellularReachability(void) {
	// This test catches only the cases when cellular reception is available
	// but WiFi is not. If WiFi is available, kSCNetworkReachabilityFlagsIsWWAN
	// is false regardless of cellular connectivity
	SCNetworkReachabilityRef target = SCNetworkReachabilityCreateWithName (NULL, "google.com");
	SCNetworkReachabilityFlags flags;
	SCNetworkReachabilityGetFlags (target, &flags);
	CFRelease (target);
	return flags & kSCNetworkReachabilityFlagsIsWWAN;
}

- (id) initWithProcessor:(ModelProcessor *)p {
	if (!self) {
		return self;
	}
	
	if ((self = [super initWithNibName:@"TiltAndSwipeViewController" bundle:nil])) {
		processor = [p retain];
		[processor startTransmission];
        
        [NSTimer scheduledTimerWithTimeInterval:0.3 target:self selector:@selector(audioWarningCallback) userInfo:nil repeats:YES];
	}
	return self;
}


- (void) audioWarningCallback {
    if (!audio_outputs_to_wire()) {
        [audioVolumeWarningLabel setText:@"Plug in iPhly or Trainer Cable"];
        [audioVolumeWarningLabel setHidden:NO];
    } else if (output_volume()<0.9) {
        [audioVolumeWarningLabel setText:@"Increase Audio Volume"];
        [audioVolumeWarningLabel setHidden:NO];
    } else if (output_volume()>0.95) {
        [audioVolumeWarningLabel setText:@"Decrease Audio Volume"];
        [audioVolumeWarningLabel setHidden:NO];
    } else {
        [audioVolumeWarningLabel setHidden:YES];
    }
}

- (NSString*)modelNameLabelText {
    return [NSString stringWithFormat:@"Now %@: %@", [swipePad gerund], [processor name]];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];

    [swipePad removeFromSuperview];
    
    // the following conditional may be a more natural fit for [TiltAndSwipePad init]
    if ([processor isCar]) {
        swipePad = [[TiltAndSwipePadCar alloc] initWithFrame:[swipePad frame] andProcessor:processor];
    } else {
        swipePad = [[TiltAndSwipePadAir alloc] initWithFrame:[swipePad frame] andProcessor:processor];
    }
    [[self view] addSubview:swipePad];
	[self setTitle:[swipePad gerund]];
    
    [[self view] addSubview:[swipePad trimmerForQuadrant:Q_TOP]];
    [[self view] addSubview:[swipePad trimmerForQuadrant:Q_RIGHT]];
    [[self view] addSubview:[swipePad trimmerForQuadrant:Q_BOTTOM]];
    [[self view] addSubview:[swipePad trimmerForQuadrant:Q_LEFT]];
    
    audioVolumeWarningLabel = [[UILabel alloc] initWithFrame:[airplaneModeWarning frame]];
    [audioVolumeWarningLabel setText:@"Volume UP"];
    [audioVolumeWarningLabel setTextAlignment:UITextAlignmentCenter];
    [audioVolumeWarningLabel setTextColor:[UIColor redColor]];
    [audioVolumeWarningLabel setHidden:YES];
    [[self view] addSubview:audioVolumeWarningLabel];
    
    
    /* all of the below is for "Slide to Configure" */
	UIImageView *sliderFrame = [[UIImageView alloc] initWithImage: [UIImage imageNamed:@"configure-slider-frame.png"]];
	[sliderFrame setFrame: CGRectMake(0,
									  [[self view] frame].size.height-[sliderFrame frame].size.height,
									  [sliderFrame frame].size.width,
									  [sliderFrame frame].size.height)];
	[[self view] addSubview:sliderFrame];
	[sliderFrame release];
	
	
	CGRect f = [sliderFrame frame];
	int verticalOffset = 2;
	f.origin.y+=verticalOffset;
	int sliderFrameHPadding = 9;
	f.origin.x+=sliderFrameHPadding;
	f.size.width-=2*sliderFrameHPadding;
	
	configureSlider = [[UISlider alloc] initWithFrame:f];
	[configureSlider setThumbImage:[UIImage imageNamed:@"configure-slider-thumb.png"] forState:UIControlStateNormal];
    [configureSlider setMaximumTrackImage:[UIImage imageNamed:@"empty.png"] forState:UIControlStateNormal];
    [configureSlider setMinimumTrackImage:[UIImage imageNamed:@"empty.png"] forState:UIControlStateNormal];
	[configureSlider addTarget:self action:@selector(sliderTouchUp) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchUpOutside];
	[configureSlider addTarget:self action:@selector(sliderValueChange) forControlEvents:UIControlEventValueChanged];
	[[self view] addSubview:configureSlider];
	[configureSlider release];
	
	configureSliderLabel = [[UILabel alloc] initWithFrame:f];
	[configureSliderLabel setTextAlignment:UITextAlignmentRight];
	[configureSliderLabel setTextColor:[UIColor darkGrayColor]];
	[configureSliderLabel setFont:[[configureSliderLabel font] fontWithSize:18]];
	[configureSliderLabel setBackgroundColor:[UIColor clearColor]];
	[configureSliderLabel setText:@"Slide to Configure   "];
	[[self view] addSubview:configureSliderLabel];
	[configureSliderLabel release];
    /* end "Slide to Configure" */
}

- (void) viewWillAppear:(BOOL)animated {
	[super viewWillAppear:animated];
	[[self navigationController] setNavigationBarHidden:YES];
    
	[modelNameLabel setText:[self modelNameLabelText]];
    
    for (UIView* v in [[self view] subviews]) {
        if ([v isKindOfClass: [TrimmerView class]]) {
            [v setNeedsDisplay];
            [v setHidden:![processor trimsVisible]];
        }
    }
    [swipePad reloadSettingsFromProcessor];
}

- (void) viewDidAppear: (BOOL) animated {
	[super viewDidAppear:animated];
	
	[[self airplaneModeWarning] setHidden: !cellularReachability()];
    [self audioWarningCallback];
	
	[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
}

- (void) viewDidDisappear: (BOOL) animated {
	if (![[self.navigationController viewControllers] containsObject:self]) {
        /*
         these reference variables that are now in TiltAndSwipePad; but I may not need these two statements at all
		[swipesFloatToCenterTimer invalidate];
		[[UIAccelerometer sharedAccelerometer] setDelegate:nil];
         */
	}
	[[UIApplication sharedApplication] setIdleTimerDisabled: NO];
	[super viewDidDisappear:animated];
}

- (void)dealloc {
	for(UIView * v in [swipePad subviews]) {
		[v removeFromSuperview];
	}
	
	[swipePad release];
	[modelNameLabel release];
	[configureBarButton release];
	[airplaneModeWarning release];
	
	[processor release];
    [super dealloc];
}

// other view controllers
- (void) showConfigurationView {
	UIViewController* vc = [[ModelConfigController alloc] initWithProcessor:processor];
	[[self navigationController] pushViewController:vc animated:YES];
	[vc release];	
}

- (void) showModelListView {
	UIViewController* vc = [[ModelListViewController alloc] init];
	[[self navigationController] pushViewController:vc animated:YES];
	[vc release];
}

- (void) showGlobalSettings {
	UIViewController* vc = [[GlobalSettingsViewController alloc] initWithProcessor:processor];
	[[self navigationController] pushViewController:vc animated:YES];
	[vc release];
}

- (void) showConfigurationAS {
	[[[[UIActionSheet alloc] initWithTitle:nil
								  delegate:self
						 cancelButtonTitle:[NSString stringWithFormat:@"Back to %@", [swipePad gerund]]
					destructiveButtonTitle:nil
						 otherButtonTitles:CONFIGURE_MODEL,
                                           CHOOSE_MODEL,
                                           GLOBAL_SETTINGS,
                                           WATCH_VIDEO,
                                           ORDER_HARDWARE,
										   ABOUT, nil]
	  autorelease] showInView:[self view]];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
	if ([actionSheet buttonTitleAtIndex:buttonIndex]==CONFIGURE_MODEL) {
		[[self navigationController] setNavigationBarHidden:NO];
		[self showConfigurationView];
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==CHOOSE_MODEL) {
		[[self navigationController] setNavigationBarHidden:NO];
		[self showModelListView];
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==GLOBAL_SETTINGS) {
		[[self navigationController] setNavigationBarHidden:NO];
		[self showGlobalSettings];
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==WATCH_VIDEO) {
		NSURL *URL = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"iPhly-intro" ofType:@"m4v"]];
        MPMoviePlayerController* mpc = [[MPMoviePlayerController alloc] initWithContentURL: URL];
        [[NSNotificationCenter defaultCenter] addObserver: self
                                                 selector: @selector(mpcFinish:)         
                                                     name: MPMoviePlayerPlaybackDidFinishNotification         
                                                   object: mpc];
		[processor stopTransmission];
        [mpc play];
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==ORDER_HARDWARE) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString: @"http://www.iphly.org/ks"]];
	} else if ([actionSheet buttonTitleAtIndex:buttonIndex]==ABOUT) {
		[[self navigationController] setNavigationBarHidden:NO];
		NSURL *URL = [NSURL fileURLWithPath: [[NSBundle mainBundle] pathForResource:@"about-iphly" ofType:@"html"]];
		WebViewController* wvc = [[[WebViewController alloc]initWithAddress:URL andTitle:@"About iPhly"] autorelease];
        NSString* version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
        [wvc setDocumentOnLoad:[NSString stringWithFormat:@"document.getElementById('version').innerHTML = 'version %@'", version]];
		[[self navigationController] pushViewController:wvc animated:YES];
	}
}

- (void) mpcFinish: (NSNotification*) n {
    MPMoviePlayerController* mpc = [n object];
    [[NSNotificationCenter defaultCenter] removeObserver: self
                                                    name: MPMoviePlayerPlaybackDidFinishNotification
                                                  object: mpc];
    [mpc release];
    [processor startTransmission];
}

- (void) sliderTouchUp {
	UISlider *s = configureSlider;
	if ([s value] == [s maximumValue]) {
		[self showConfigurationAS];
	}
	[s setValue:[s minimumValue]];
    [configureSliderLabel setAlpha:1];
}

- (void) sliderValueChange {
	[configureSliderLabel setAlpha:1-3*[configureSlider value]];
}


@end
