#import "ManageTunesController.h"
#import "ImportABCController.h"
#import "AppDelegate.h"

@implementation ManageTunesController

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

#define kImportTunes  0
#define kDeleteTunes  1

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

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

- (void)didReceiveMemoryWarning
{
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview.
	// Release anything that's not essential, such as cached data.
}

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

#pragma mark UITableView delegate methods

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

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	[tableView deselectRowAtIndexPath:indexPath animated:YES];

  int row = indexPath.row;
  if ( indexPath.section == 0 ) {
    if ( row == kImportTunes ) {
      ImportABCController *controller = [[ImportABCController alloc] initWithNibName:@"ImportTunes" bundle:nil];
      [self.navigationController pushViewController:controller animated:YES];
    } else if ( row == kDeleteTunes ) {
      UIActionSheet *sheet = [[UIActionSheet alloc]
        initWithTitle:@"Delete Tunes"
        delegate:self
        cancelButtonTitle:@"Don't Delete"
        destructiveButtonTitle:@"Delete"
        otherButtonTitles:nil
      ];
      [sheet showInView:self.view];
    }
  }
}

#pragma mark UITableView data source methods

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  return section == 0 ? 2 : 1;
}

- (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section {
	return @"Manage Tunes";
}

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	UITableViewCell *cell = [tv dequeueReusableCellWithIdentifier:kCellIdentifier];
	if (cell == nil)
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:kCellIdentifier] autorelease];

  int row = indexPath.row;
  if ( indexPath.section == 0 ) {
    if ( row == kImportTunes )
      cell.text = @"Import Tunes";
    else if ( row == kDeleteTunes )
      cell.text = @"Delete All Tunes";
  }
	return cell;
}

#pragma mark UIActionSheetDelegate methods

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
  if ( buttonIndex == 0 ) {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate deleteAllTunes];
  }
}

@end
