#import "AppDelegate.h"
#import "MainViewController.h"
#import "ManageTunesController.h"

@implementation AppDelegate

@synthesize tunes;

- (void)dealloc
{
  [tunes release];    
	[navigationController release];
  [window release];    
  [super dealloc];
}

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
  [navigationController.navigationBar setBarStyle:UIBarStyleDefault];
	[window addSubview: navigationController.view];
	[window makeKeyAndVisible];
}

- (void)createEditableCopyOfDatabaseIfNeeded {
  BOOL success;
  NSFileManager *fileManager = [NSFileManager defaultManager];
  NSError *error;
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"tunedb.sql"];
  success = [fileManager fileExistsAtPath:writableDBPath];
  if ( success )
    return;

  NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"tunedb.sql"];
  success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
  if (!success) {
    NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
  }
}

- (void)initializeDatabase {
  NSMutableArray *tuneArray = [[NSMutableArray alloc] init];
  self.tunes = tuneArray;
  [tuneArray release];
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
  NSString *documentsDirectory = [paths objectAtIndex:0];
  NSString *path = [documentsDirectory stringByAppendingPathComponent:@"tunedb.sql"];
  
  if ( sqlite3_open([path UTF8String], &database) == SQLITE_OK ) {
    const char *sql = "SELECT pk FROM tune";
    sqlite3_stmt *statement;
    if ( sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK ) {
      while ( sqlite3_step(statement) == SQLITE_ROW ) {
        int primaryKey = sqlite3_column_int(statement, 0);
        Tune *tune = [[Tune alloc] initWithPrimaryKey:primaryKey database:database];
        [tunes addObject:tune];
        [tune release];
      }
    }
    sqlite3_finalize(statement);
  } else {
    sqlite3_close(database);
    NSAssert1(0, @"Failed to open database with message '%s'.", sqlite3_errmsg(database));
  }

  [Tune finalizeStatements];
}

- (void)applicationWillTerminate:(UIApplication *)application {
  [tunes makeObjectsPerformSelector:@selector(dehydrate)];
  [Tune finalizeStatements];
  if (sqlite3_close(database) != SQLITE_OK) {
    NSAssert1(0, @"Error: failed to close database with message '%s'.", sqlite3_errmsg(database));
  }
}

- (void)removeTune:(Tune *)tune {
  [tune deleteFromDatabase];
  [tunes removeObject:tune];
}

- (void)addTune:(Tune *)tune {
  [tune insertIntoDatabase:database];
  [tunes addObject:tune];
}

-(void)onImportTunes:(id)sender {
  ManageTunesController *controller = [[ManageTunesController alloc] initWithNibName:@"ManageTunes" bundle:nil];
	[navigationController pushViewController:controller animated:YES];
}

- (void)deleteAllTunes {
  printf("delete %d\n", 
  sqlite3_exec( database, "DELETE FROM tune", NULL, NULL, NULL )
  );
  [tunes removeAllObjects];
  [[NSNotificationCenter defaultCenter] postNotificationName:@"databaseChanged" object:self]; 
}

@end

