//
//  RootViewController.m
//  Sqlite
//
//  David J. Malan
//  Harvard University
//  dmalan@harvard.edu
//
//  Demonstrates SQLite.
//

#import "RootViewController.h"

@implementation RootViewController

@synthesize words=_words;

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // allocate cell, reusing if possible
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    
    // configure cell
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.textLabel.text = [self.words objectAtIndex:[indexPath row]];
    
    return cell;
}

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

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // prepare for words
    NSMutableArray *words = [[NSMutableArray alloc] init];

    // connect to SQLite database
    sqlite3 *db;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"sqlite"];
    sqlite3_open([path UTF8String], &db);    

    // select four-letter words words
    NSString *sql = @"SELECT word FROM words WHERE LENGTH(word) = 4";
    sqlite3_stmt *statement;
    sqlite3_prepare_v2(db, [sql UTF8String], -1, &statement, nil);

    // iterate over results
    while (sqlite3_step(statement) == SQLITE_ROW) {
        char *c = (char *) sqlite3_column_text(statement, 0);
        NSString *s = [[NSString alloc] initWithUTF8String:c];
        [words addObject:s];
        [s release];
    }

    // close database
    sqlite3_close(db);
    
    // retain words
    self.words = words;
    [words release];
}

@end
