#import "TunePlayerController.h"
#import "EditABCController.h"
#import "Tune.h"
#import "TunePlayer.h"

@implementation TunePlayerController

@synthesize tune;

-(id<TuneViewDelegate>)tuneViewDelegate
{
	return tuneView.delegate;
}

-(void)setTuneViewDelegate:(id<TuneViewDelegate>)delegate
{
	tuneView.delegate = [delegate retain];
}

-(id)initWithTitle:(NSString*)title;
{
	self = [super init];
	if ( self != nil ) {
		self.title = title;

		tuneView = [[TuneView alloc] initWithFrame:CGRectMake(0.0, 0.0, 1.0, 1.0)];
		tuneView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    tuneView.scale = 1.0f;
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewTapped:) name:@"tap" object:nil]; 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(viewDoubleTapped:) name:@"doubleTap" object:nil]; 
	}
	return self;
}

-(void)loadView
{
  [self navigationController].navigationBar.barStyle = UIBarStyleBlackTranslucent;
	scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
	[scrollView setContentSize:CGSizeMake(576 * kTuneScale, 792 * kTuneScale)];
	[scrollView setScrollEnabled:YES];
  scrollView.minimumZoomScale = 0.5f;
  scrollView.maximumZoomScale = 6.0f;
  scrollView.delegate = self;
	scrollView.autoresizesSubviews = YES;
  scrollView.clipsToBounds = YES;
	scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth;
	self.view = scrollView;
//	tuneView.frame = view.bounds;
	tuneView.frame = CGRectMake( 0, 0, 576 * kTuneScale, 792 * kTuneScale );
  tuneView.tune = tune;
  tuneView.contentMode = UIViewContentModeRedraw;
  tuneView.tuneTransform = CGAffineTransformIdentity;

	[scrollView addSubview:tuneView];

	[scrollView release];

  UIBarButtonItem *editButton = [[[UIBarButtonItem alloc]
    initWithTitle:@"ABC"
    style:UIBarButtonItemStylePlain 
    target:self 
    action:@selector(editABC)] autorelease];
  self.navigationItem.rightBarButtonItem = editButton;
//  self.navigationController.delegate = self;
}

- (void)editABC {
  NSString *directory = NSTemporaryDirectory();
  NSString *abcPath = [directory stringByAppendingPathComponent:@"tune.abc"];
  NSString *midiPath = [directory stringByAppendingPathComponent:@"tune.mid"];

  NSError *error = NULL;
  if ( [[tune dots] writeToFile:abcPath atomically:false encoding:NSUTF8StringEncoding error:&error] ) {
    const char *argv[] = {
      "abc2midi",
      [abcPath UTF8String],
      "-o",
      [midiPath UTF8String],
      NULL
    };
    extern int abc2midi_main(int argc, char *argv[]);
    abc2midi_main( 4, (char *)argv );
    NSData *data = [NSData dataWithContentsOfFile:midiPath];
    TunePlayer *player = [[TunePlayer alloc] initWithData:data];
    [player play];
  }


  EditABCController *controller = [EditABCController alloc];
  [controller initWithTitle:tune.title];
  controller.tune = tune;
//  [self presentModalViewController:controller animated:YES];
	[[self navigationController] pushViewController:controller animated:YES];
  [controller autorelease];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
  return YES;
}

- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning];
}

-(void)dealloc {
	[tuneView.delegate release];
	[tuneView release];
	[super dealloc];
}

- (IBAction)hideStatusBar {	
  UINavigationBar *navigationBar = self.navigationController.navigationBar;
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  [UIView setAnimationDuration:1.0];
  [navigationBar setAlpha:0.0f];
  [UIView commitAnimations];
}

- (IBAction)showStatusBar {	
  UINavigationBar *navigationBar = self.navigationController.navigationBar;
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  [UIView setAnimationDuration:0.5f];
  [navigationBar setAlpha:1.0f];
  [UIView commitAnimations];
}

- (void)viewTapped:(id)sender {
  UINavigationBar *navigationBar = self.navigationController.navigationBar;
  if ( navigationBar.alpha != 1 )
    [self showStatusBar];
  else
    [self hideStatusBar];
}

- (void)viewDoubleTapped:(id)sender {
	CGAffineTransform transform = CGAffineTransformIdentity;
  tuneView.transform = transform;
	tuneView.frame = CGRectMake( 0, 0, 576*kTuneScale, 792*kTuneScale );
	scrollView.contentSize = CGSizeMake( 576*kTuneScale, 792*kTuneScale );
  scrollView.contentOffset = CGPointMake(0.0f, 0.0f);
  [tuneView setNeedsLayout];
  [tuneView setNeedsDisplay];
  [self hideStatusBar];
}

#pragma mark UIViewController delegate methods

- (void)viewWillAppear:(BOOL)animated
{
	[[UIApplication sharedApplication] setStatusBarStyle:UIBarStyleBlackTranslucent animated:YES];
  [self navigationController].navigationBar.barStyle = UIBarStyleBlackTranslucent;
//  [self hideStatusBar];
}

- (void)viewWillDisappear:(BOOL)animated
{
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
  return tuneView;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale;
{
  tuneView.scale = scale;
//	CGAffineTransform transform = CGAffineTransformIdentity;
//	transform = CGAffineTransformScale( transform, scale, scale );
	tuneView.frame = CGRectMake( 0, 0, 576*scale*kTuneScale, 792*scale*kTuneScale );
  [tuneView setNeedsDisplay];
}

#pragma mark UIAlertView delegate methods

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
  if ( buttonIndex == 1 ) {
    [tune dehydrate];
  }
}

- (BOOL)navigationBar:(UINavigationBar *)navigationBar shouldPopItem:(UINavigationItem *)item;  // same as push methods
{
  if ( [tune dirty] ) {
    UIAlertView *alert = [[UIAlertView alloc] 
      initWithTitle: @"Save Changes" 
      message:@"Save changes to the tune?" 
      delegate:self 
      cancelButtonTitle:@"Don't Save" 
      otherButtonTitles:@"Save", nil];
    [alert show];
    return false;
  }
  return true;
}

@end
