#import "EditABCController.h"
#import "TuneViewController.h"
#import "Tune.h"
#import "AppDelegate.h"

@implementation EditABCController

@synthesize changed;
#if TARGET_IPAD
@synthesize editTune;
@synthesize tuneViewController;
#endif

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

    self.view = [[UIView alloc] initWithFrame:frame];
    self.view.autoresizesSubviews = YES;
    self.view.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;

    textView = [[UITextView alloc] initWithFrame:frame];
    textView.font = [UIFont systemFontOfSize:14];
    textView.autoresizesSubviews = YES;
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
    textView.autocapitalizationType = UITextAutocapitalizationTypeNone;
    textView.autocorrectionType = UITextAutocorrectionTypeNo;
    textView.keyboardType = UIKeyboardTypeASCIICapable;
    textView.delegate = self;
    [self.view addSubview: textView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    [textView release];
	}
	return self;
}

- (void)keyboardWillShow:(NSNotification *)notification
{
  NSDictionary *info = [notification userInfo];
  NSValue *keyBounds = [info objectForKey:UIKeyboardBoundsUserInfoKey];
  CGRect keyboardBounds;
  [keyBounds getValue:&keyboardBounds];

#if TARGET_IPAD
  CGRect frame = self.view.frame;
  savedFrame = frame;
  switch ( self.interfaceOrientation ) {
  case UIInterfaceOrientationPortrait:
    frame.size.height -= keyboardBounds.size.height;
    break;
  case UIInterfaceOrientationPortraitUpsideDown:
    frame.size.height -= keyboardBounds.size.height;
    frame.origin.y += keyboardBounds.size.height;
    break;
  case UIInterfaceOrientationLandscapeLeft:
    frame.size.width -= keyboardBounds.size.height;
    break;
  case UIInterfaceOrientationLandscapeRight:
    frame.size.width -= keyboardBounds.size.height;
    frame.origin.x += keyboardBounds.size.height;
    break;
  }
  self.view.frame = frame;
  [self layoutViews:self.interfaceOrientation];
#else
  CGRect frame = self.view.bounds;
  frame.size.height -= keyboardBounds.size.height;
  textView.frame = frame;
#endif
//  NSRange range = [textView selectedRange];
// This is too prone to crashing....
//  if ( range.length >= 0 && range.location != (NSUInteger)-1 )
//    [textView scrollRangeToVisible:[textView selectedRange]];
}

- (void)keyboardWillHide:(id)sender
{
#if TARGET_IPAD
  self.view.frame = [UIScreen mainScreen].applicationFrame;
  [self layoutViews:self.interfaceOrientation];
#else
//  textView.frame = [UIScreen mainScreen].applicationFrame;
  textView.frame = self.view.bounds;
#endif
}

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

#if TARGET_IPAD
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
  [self layoutViews:toInterfaceOrientation];
}

- (void)layoutViews:(UIInterfaceOrientation)orientation
{
  CGRect bounds = self.view.bounds;
  float w = bounds.size.width;
  float h = bounds.size.height;
  float t = 44; // toolbar height
  if ( UIInterfaceOrientationIsPortrait(orientation) ) {
    textView.frame = CGRectMake( 0, h/2, w, h/2 );
    tuneViewController.view.frame = CGRectMake( 0, t, w, h/2-t );
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleHeight;
    tuneViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
  } else {
    textView.frame = CGRectMake( 0, t, w/2, h-t );
    tuneViewController.view.frame = CGRectMake( w/2, t, w/2, h-t );
    textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleHeight;
    tuneViewController.view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleHeight;
  }
}

// For iOS 6.0
- (BOOL)shouldAutorotate {
//    if ([self.topViewController respondsToSelector:@selector(shouldAutorotate)]) {
//        return [self.topViewController shouldAutorotate];
//    }
    return YES;
}

- (NSUInteger)supportedInterfaceOrientations {
//    if ([self.topViewController respondsToSelector:@selector(supportedInterfaceOrientations)]) {
//        return [self.topViewController supportedInterfaceOrientations];
//    }
    return UIInterfaceOrientationMaskAll;
}
#endif

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

-(void)dealloc
{
#if TARGET_IPAD
  [tune dealloc];
#endif
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	[super dealloc];
}

#pragma mark UIViewController delegate methods

#if TARGET_IPAD
-(void)viewDidLoad {
  textView.text = editTune.dots;
  textView.delegate = self;
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
  tune = [[Tune alloc] init];
  tune.temporary = YES;
  tune.hydrated = YES;
  tune.dots = editTune.dots;
  [self layoutViews:self.interfaceOrientation];
  [tuneViewController showTune:tune];
//  textView.inputAccessoryView = accessoryView;    
}
#endif

- (void)viewWillAppear:(BOOL)animated
{
#if TARGET_IPAD
  [tuneViewController zoomToFit:self];
#endif
}

- (void)viewDidAppear:(BOOL)animated
{
#if !TARGET_IPAD
  [self navigationController].navigationBar.backItem.title = @"Back";
#endif
}

#pragma mark UITextViewDelegate delegate methods

- (void)textViewDidChange:(UITextView *)textView
{
  changed = YES;
#if TARGET_IPAD
  [self previewPressed:self];
#endif
}

-(void)setText:(NSString*)text
{
  textView.text = text;
#if TARGET_IPAD
  tune.dots = text;
#endif
  changed = NO;
}

-(NSString *)text
{
  return textView.text;
}

#if TARGET_IPAD
- (IBAction)previewPressed:(id)sender
{
  tune.dots = self.text;
  [tuneViewController dotsChanged];
}

- (IBAction)cancelPressed:(id)sender
{
  [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)donePressed:(id)sender
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  numTunes = 0;
  parsedTunes = [[NSMutableArray alloc] init];
  [parsedTunes retain];
  TuneParser *parser = [[TuneParser alloc] init];
  parser.delegate = self;
  NSString *dots = textView.text;
  [parser parseString:dots];
  if ( numTunes == 0 ) {
    UIAlertView *alert = [[UIAlertView alloc] 
      initWithTitle: @"Bad ABC" 
      message:@"The ABC does not contain any valid tunes." 
      delegate:nil
      cancelButtonTitle:nil 
      otherButtonTitles:@"OK", nil];
    [alert show];
    [parsedTunes release];
  } else if ( numTunes > 1 ) {
    multipleTunesSheet = [[UIActionSheet alloc]
      initWithTitle:[NSString stringWithFormat:@"Multiple tunes in ABC"]
      delegate:self
      cancelButtonTitle:@"Cancel"
      destructiveButtonTitle:@"Add Extra Tunes"
      otherButtonTitles:nil
    ];
    [multipleTunesSheet showInView:self.view];
  } else {
    Tune *t = (Tune *)[parsedTunes objectAtIndex:0];
    editTune.title = t.title;//FIXME-method to do this...
    editTune.dots = t.dots;
    editTune.rating = t.rating;
    editTune.key = t.key;
    editTune.numSharps = t.numSharps;
    editTune.timeSigNum = t.timeSigNum;
    editTune.timeSigDen = t.timeSigDen;
    if ( [editTune inDatabase] ) {
      [editTune dehydrate];
      [editTune hydrate];
    } else
      [appDelegate addTune:editTune];
    [parsedTunes release];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"databaseChanged" object:self]; 
    [appDelegate.tuneViewController showTune:editTune];
    [self dismissModalViewControllerAnimated:YES];
  }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if ( buttonIndex == 0 ) {
    Tune *t = (Tune *)[parsedTunes objectAtIndex:0];
    editTune.title = t.title;
    editTune.dots = t.dots;
    editTune.rating = t.rating;
    editTune.key = t.key;
    editTune.numSharps = t.numSharps;
    editTune.timeSigNum = t.timeSigNum;
    editTune.timeSigDen = t.timeSigDen;
    if ( [editTune inDatabase] )
      [editTune dehydrate];
    else
      [appDelegate addTune:editTune];

    // Add the extra tunes
    for ( int i = 1; i < [parsedTunes count]; i++ )
      [appDelegate addTune:(Tune *)[parsedTunes objectAtIndex:i]];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"databaseChanged" object:self]; 
  }
  [parsedTunes release];
  [self dismissModalViewControllerAnimated:YES];
}

- (void) parsedTune:(TuneParser *)parser tune:(Tune *)t
{
  numTunes++;
  [parsedTunes addObject:t];
}
#endif

@end
