//
//  QuranSearchViewController.m
//  QuranSearch
//
//  Created by Ahmed El-Helw on 10/21/10.
//  Copyright 2010 None. All rights reserved.
//

#import "Ayah.h"
#import "QuranSearchViewController.h"

@implementation QuranSearchViewController
@synthesize resultsTable;
@synthesize suggestions;
@synthesize lastQuery;
@synthesize database;
@synthesize suraNames;
@synthesize selectedAyahIndex;
@synthesize delegate;

- (void)viewDidLoad {
    [super viewDidLoad];
	if ([self lastQuery])
		[[[self searchDisplayController] searchBar] setText:[self lastQuery]];
	
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
		[self setContentSizeForViewInPopover:CGSizeMake(320.0, 300.0)];
	
	if ([self database] == nil){
		[self setDatabase:[QuranDatabase alloc]];
		[database initialize];
	}
	
	NSArray *array = [[NSArray alloc] initWithObjects:
					  @"Al-Fatiha", @"Al-Baqara", @"Aal-E-Imran", @"An-Nisa", 
					  @"Al-Maeda", @"Al-Anaam", @"Al-Araf", @"Al-Anfal",
					  @"At-Tawba", @"Yunus", @"Hud", @"Yusuf", @"Ar-Rad",
					  @"Ibrahim", @"Al-Hijr", @"An-Nahl", @"Al-Isra",
					  @"Al-Kahf", @"Maryam", @"Ta-Ha", @"Al-Anbiya", @"Al-Hajj",
					  @"Al-Mumenoon", @"An-Noor", @"Al-Furqan", @"Ash-Shu'ara",
					  @"An-Naml", @"Al-Qasas", @"Al-Ankaboot", @"Ar-Room",
					  @"Luqman", @"As-Sajda", @"Al-Ahzab", @"Saba",
					  @"Fatir", @"Ya-Seen", @"As-Saaffat", @"Sad", @"Az-Zumar",
					  @"Ghafir", @"Fussilat", @"Ash-Shura", @"Az-Zukhruf",
					  @"Ad-Dukhan", @"Al-Jathiya", @"Al-Ahqaf", @"Muhammad",
					  @"Al-Fath", @"Al-Hujraat", @"Qaf", @"Adh-Dhariyat",
					  @"At-Tur", @"An-Najm", @"Al-Qamar", @"Ar-Rahman",
					  @"Al-Waqia", @"Al-Hadid", @"Al-Mujadila", @"Al-Hashr",
					  @"Al-Mumtahina", @"As-Saff", @"Al-Jumua",
					  @"Al-Munafiqoon", @"At-Taghabun", @"At-Talaq",
					  @"At-Tahrim", @"Al-Mulk", @"Al-Qalam", @"Al-Haaqqa",
					  @"Al-Maarij", @"Nooh", @"Al-Jinn", @"Al-Muzzammil",
					  @"Al-Muddaththir", @"Al-Qiyama", @"Al-Insan",
					  @"Al-Mursalat", @"An-Naba", @"An-Naziat", @"Abasa",
					  @"At-Takwir", @"Al-Infitar", @"Al-Mutaffifin",
					  @"Al-Inshiqaq", @"Al-Burooj", @"At-Tariq",
					  @"Al-Ala", @"Al-Ghashiya", @"Al-Fajr", @"Al-Balad",
					  @"Ash-Shams", @"Al-Lail", @"Ad-Dhuha", @"Al-Inshirah",
					  @"At-Tin", @"Al-Alaq", @"Al-Qadr", @"Al-Bayyina",
					  @"Az-Zalzala", @"Al-Adiyat", @"Al-Qaria", @"At-Takathur",
					  @"Al-Asr", @"Al-Humaza", @"Al-Fil", @"Quraish",
					  @"Al-Maun", @"Al-Kauther", @"Al-Kafiroon", @"An-Nasr",
					  @"Al-Masadd", @"Al-Ikhlas", @"Al-Falaq",
					  @"An-Nas", nil];
	[self setSuraNames:array];
	[array release];
}

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

- (void)search:(NSString *)query {
	[self setLastQuery:query];
	
	if ([self suggestions] == nil){
		NSMutableArray *array = [[NSMutableArray alloc] init];
		[self setSuggestions:array];
		[array release];
	}
	
	[[self suggestions] removeAllObjects];
	
	if ([query length] > 1){
		NSArray* results = [database autocomplete:query];

		for (NSString* ayah in results)
			[[self suggestions] addObject:ayah];
	}
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchStr {
	[self search: searchStr];
}

- (UITableViewCell *)tableView:(UITableView *)tableView
		             cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	Ayah *content = [[self suggestions] objectAtIndex:[indexPath row]];
	
	UITableViewCell *cell =
		[tableView dequeueReusableCellWithIdentifier:@"SearchResult"];
	if (cell == nil){
		cell = [[[UITableViewCell alloc]
				 initWithStyle:UITableViewCellStyleSubtitle
				 reuseIdentifier:@"SearchResult"] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
	}
	
	[[cell textLabel] setText:content.translation];
	[[cell detailTextLabel] setText:[NSString 
									 stringWithFormat:@"Surat %s, ayah %d", 
									 [[[self suraNames] 
									   objectAtIndex:(content.sura-1)]
									  UTF8String], content.ayah]];
	return cell;
}

- (void)tableView:(UITableView *)tableView
	didSelectRowAtIndexPath:(NSIndexPath *)indexPath {	
	[self setSelectedAyahIndex:[indexPath row]];
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
		Ayah *selected = [[self suggestions]
						  objectAtIndex:[self selectedAyahIndex]];
		if (delegate != nil)
			[delegate resultSelectionChanged:selected];
	}
	else [self showActionSheet: self];
}

- (IBAction)showActionSheet:(id)sender {
	UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:nil
		delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil
		otherButtonTitles:@"View on Quran.com",
						  @"Listen on EveryAyah.com", nil];
	popupQuery.actionSheetStyle = UIActionSheetStyleDefault;
	[popupQuery showInView:self.view];
	[popupQuery release];
}

- (void)actionSheet:(UIActionSheet *)actionSheet
		clickedButtonAtIndex:(NSInteger)buttonIndex {
	NSURL *url = nil;
	Ayah *sel = [[self suggestions] objectAtIndex:[self selectedAyahIndex]];
	if (buttonIndex == 0){
		NSString* urlText = [[[NSString alloc]
			initWithFormat:@"http://quran.com/%d/%d", sel.sura, sel.ayah, nil]
							 autorelease];
		url = [NSURL URLWithString:urlText];
	}
	else if (buttonIndex == 1){
		NSString* urlText = [[[NSString alloc]
			initWithFormat:@"%s/%03d%03d.mp3",
			[@"http://www.everyayah.com/data/Alafasy_128kbps" UTF8String],
			sel.sura, sel.ayah, nil] autorelease];
		url = [NSURL URLWithString:urlText];
	}
	
	if (url != nil)
		[[UIApplication sharedApplication] openURL:url];
}


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

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

- (void)viewDidUnload {
	[self setLastQuery:[[[self searchDisplayController] searchBar] text]];
	[self setSuggestions:nil];
}

- (void)dealloc {
	[resultsTable release];
	[suggestions release];
	[lastQuery release];
	[suraNames release];
	delegate = nil;
	[database close];
	[QuranDatabase release];
    [super dealloc];
}

@end
