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

#define kCellIdentifier @"com.jhlabs.Tunebook.TuneCellIdentifier"

@implementation MainViewController

@synthesize listContent, filteredListContent, tableView, searchBar;

-(void)awakeFromNib {
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [appDelegate createEditableCopyOfDatabaseIfNeeded];
  [appDelegate initializeDatabase];
	searchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;

	listContent = appDelegate.tunes;
	
	filteredListContent = [[NSMutableArray alloc] initWithCapacity: [listContent count]];
	[filteredListContent addObjectsFromArray: listContent];
	
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(databaseChanged:) name:@"databaseChanged" object:nil]; 
}

- (void)dealloc {
	[tableView dealloc];
	[searchBar release];
	[listContent release];
	[filteredListContent release];

  [super dealloc];
}

- (void)databaseChanged:(id)sender {
	[filteredListContent removeAllObjects];
  [filteredListContent addObjectsFromArray: listContent];
	[tableView reloadData];
}

- (IBAction)onSearch:(id)sender {
  CGRect sr = searchBar.bounds;
  CGRect tr = tableView.bounds;
  if ( searchBar.hidden ) {
    sr.origin.y -= 44;
    tr.size.height -= 88;
  } else {
    sr.origin.y += 44;
    tr.size.height += 88;
  }
  [UIView beginAnimations:nil context:NULL];
  [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
  [UIView setAnimationDuration:0.4f];
  [searchBar setAlpha:searchBar.hidden ? 1.0f : 0.0f];
  [tableView setBounds:tr];
  searchBar.hidden = !searchBar.hidden;
  [UIView commitAnimations];
  if ( searchBar.hidden )
    [searchBar resignFirstResponder];
  else
    [searchBar becomeFirstResponder];
}

#pragma mark UIViewController delegate

- (void)viewWillAppear:(BOOL)animated
{
	NSIndexPath *tableSelection = [tableView indexPathForSelectedRow];
	[tableView deselectRowAtIndexPath:tableSelection animated:NO];
  tableView.rowHeight = 34;
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
}

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

#pragma mark UITableView delegate methods

- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath
{
	return UITableViewCellAccessoryDisclosureIndicator;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	if ( [searchBar isFirstResponder] )
    [searchBar resignFirstResponder];
  Tune *tune = (Tune *)[filteredListContent objectAtIndex:indexPath.row];
  [tune hydrate];
  TuneViewController *controller = [[TuneViewController alloc] initWithTune:tune];
	[[self navigationController] pushViewController:controller animated:YES];
  [controller autorelease];
}

#pragma mark UITableView data source methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return [filteredListContent count];
}

#define ROW_HEIGHT 24
#define kTitleTag 1
#define kKeyTag 2
#define kTimeTag 3

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];
	
	if (cell == nil)
		cell = [self tableviewCellWithReuseIdentifier:kCellIdentifier];
	
  Tune *tune = (Tune *)[filteredListContent objectAtIndex:indexPath.row];

	UILabel *label;
  label = (UILabel *)[cell viewWithTag:kTitleTag];
  label.text = tune.title;

  label = (UILabel *)[cell viewWithTag:kKeyTag];
  label.text = tune.key;
  if ( tune.timeSigDen != 0 ) {
    label.text = [NSString stringWithFormat:@"%d/%d %@", tune.timeSigNum, tune.timeSigDen, label.text];
  }

	return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tv editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
  return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    Tune *tune = (Tune *)[filteredListContent objectAtIndex:indexPath.row];
    [appDelegate removeTune:tune];
    [filteredListContent removeObject:tune];
    [tv reloadData];
	}
}

- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier {
	
  CGRect bounds = [tableView bounds];
	CGRect rect = CGRectMake(0.0, 0.0, bounds.size.width, ROW_HEIGHT);
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:identifier] autorelease];
	
	UILabel *label;
	
	rect = CGRectMake( 8, 3, bounds.size.width-30, 14 );
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = kTitleTag;
	label.font = [UIFont boldSystemFontOfSize:15];
	label.adjustsFontSizeToFitWidth = NO;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	
	rect = CGRectMake( 8, 20, bounds.size.width-30, 10);
	label = [[UILabel alloc] initWithFrame:rect];
	label.tag = kKeyTag;
	label.font = [UIFont systemFontOfSize:12];
	label.adjustsFontSizeToFitWidth = NO;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	return cell;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)bar
{
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)bar
{
}

- (void)searchBar:(UISearchBar *)bar textDidChange:(NSString *)searchText
{
	[filteredListContent removeAllObjects];
	
	if ( searchText.length > 0 ) {
    Tune *tune;
    NSArray *words = [searchText componentsSeparatedByString:@" "];
    int count = [words count];
    if ( count == 0 )
      return;

    int tsi = -1, tsn = 0, tsd = 0;
    for ( int j = 0; j < count; j++ ) {
      NSString *word = [words objectAtIndex:j];
      if ( sscanf( [word UTF8String], "%d/%d", &tsn, &tsd ) == 2 ) {
        tsi = j;
        break;
      }
    }
    
    for ( tune in listContent ) {
      BOOL add = true;
      NSString *title = tune.title;
      NSString *key = tune.key;

      if ( tsi != -1 && (tune.timeSigNum != tsn || tune.timeSigDen != tsd) )
        add = false;

      for ( int j = 0; add && j < count; j++ ) {
        NSString *word = [words objectAtIndex:j];
        if ( j != tsi && word.length != 0 ) {
          NSRange range;
          range.length = 0;
          if ( word.length > 1 )
            range = [title rangeOfString:word options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
          if ( range.length == 0 ) {
            range = [key rangeOfString:word options:NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch];
            if ( range.length == 0 )
              add = false;
          }
        }
      }
      if ( add )
        [filteredListContent addObject:tune];
    }
  } else {
		[filteredListContent addObjectsFromArray: listContent];
  }
	
	[tableView reloadData];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)bar
{
	if ( bar.text.length > 0 ) {
		[filteredListContent removeAllObjects];
		[filteredListContent addObjectsFromArray: listContent];
	}
	
	[tableView reloadData];

	[bar resignFirstResponder];
	bar.text = @"";
  [self onSearch:self];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)bar
{
	[bar resignFirstResponder];
}

@end
