#import "PlaylistViewController.h"
#import "MainViewController.h"
#import "AppDelegate.h"
#import "EditTextTableCell.h"
#if 0//FIXME-NEWUI
#import "TunebookCell.h"
#import "QuartzCore/CAGradientLayer.h"
#endif

#define kCellIdentifier @"com.jhlabs.tunebook.PlaylistCellIdentifier"

@implementation PlaylistViewController

@synthesize data, tableView;
@synthesize tunesController;

#if TARGET_IPAD
- (CGSize)contentSizeForViewInPopoverView
{
  return CGSizeMake(320.0, 440.0);
}
#endif

-(void)awakeFromNib {
  tunesController = 0;
}

-(void)viewDidLoad {
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(databaseChanged:) name:@"databaseChanged" object:nil]; 
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(databaseChanged:) name:@"databaseLoaded" object:nil]; 
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(databaseChanged:) name:@"playlistsChanged" object:nil]; 
  self.tableView.scrollsToTop = NO;
#if TARGET_IPAD
  UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addTunebook:)];
  self.navigationItem.leftBarButtonItem = addButton;
  [addButton release];
  self.navigationItem.rightBarButtonItem = self.editButtonItem;
  self.navigationItem.title = @"Tunebooks";
#endif
}

- (void)dealloc {
	[tableView dealloc];

  [super dealloc];
}

- (void)databaseChanged:(id)sender
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  data = appDelegate.playlists;
	[tableView reloadData];
}

#pragma mark UIViewController delegate

- (void)viewWillAppear:(BOOL)animated
{
	NSIndexPath *tableSelection = [tableView indexPathForSelectedRow];
	[tableView deselectRowAtIndexPath:tableSelection animated:NO];
	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.topViewController.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewWillDisappear:(BOOL)animated
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.topViewController.navigationItem.rightBarButtonItem = nil;
}

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

- (void)setEditing:(BOOL)editing animated:(BOOL)animated {
  [super setEditing:editing animated:animated];
  NSArray *indexPaths = [NSArray arrayWithObjects:
    [NSIndexPath indexPathForRow:0 inSection:0],
    nil
  ];
  [tableView beginUpdates];
  [tableView setEditing:editing animated:YES];
  if (editing) {
    // Show the placeholder rows
    [tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
  } else {
    // Hide the placeholder rows.
    [tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationTop];
  }
  [tableView endUpdates];
}

#pragma mark UITableView delegate methods

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  Playlist *playlist = (Playlist *)[data objectAtIndex:indexPath.row];
#if 0//FIXME-NEWUI
  if ( !tunesController )
#endif
  [tv deselectRowAtIndexPath:indexPath animated:YES];
#if TARGET_IPAD
  if ( tunesController )
    tunesController.playlist = playlist;
  else {
    MainViewController *controller = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
    controller.playlist = playlist;
    [[self navigationController] pushViewController:controller animated:YES];
  }
#else
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  MainViewController *controller = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
  controller.playlist = playlist;
  [appDelegate.navigationController pushViewController:controller animated:YES];
#endif
}

- (void)tableView:(UITableView *)tv accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
  Playlist *playlist = (Playlist *)[data objectAtIndex:indexPath.row-1]; // -1 because we're editing and have the "add" row
  detailsController.playlist = playlist;
  detailsController.tableView = tv;
  detailsController.indexPath = indexPath;
#if TARGET_IPAD
  detailsController.contentSizeForViewInPopover = CGSizeMake(320,480);
  [[self navigationController] pushViewController:detailsController animated:YES];
#else
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [appDelegate.navigationController pushViewController:detailsController animated:YES];
#endif
}

#pragma mark UITableView data source methods

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//  if ( section == 0 )
//    return 1;
  NSInteger count = [data count];
  if (self.editing)
    count++;
  return count;
}

#define kIconTag 1
#define kNameTag 2

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
#if 0//FIXME-NEWUI
	TunebookCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

  if ( cell == nil ) {
    NSArray* views = [[NSBundle mainBundle] loadNibNamed:@"TunebookCell" owner:nil options:nil];
 
    for (UIView *view in views) {
      if ( [view isKindOfClass:[UITableViewCell class]] )
        cell = (TunebookCell*)view;
    }

//    CAGradientLayer *gradient = [CAGradientLayer layer];
//    gradient.frame = cell.bounds;
//    gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor lightGrayColor]CGColor], (id)[[UIColor darkGrayColor]CGColor], nil];
//    [cell.layer insertSublayer:gradient atIndex:0];
  }

  int row = indexPath.row;
  if ( self.editing )
    row--;
  if ( self.editing && row == -1 ) {
    cell.nameView.text = @"Add new tunebook";
  } else {
    Playlist *playlist = (Playlist *)[data objectAtIndex:row];

    cell.nameView.text = playlist.name;
    cell.numTunesView.text = [NSString stringWithFormat:@"%d Tunes", 4];
    if ( playlist.type == kPlaylistTypeSearch )
      cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"smartbook.png"]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    static float version = 0;
    if ( version == 0 )
      version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if ( version >= 3.0 )
      cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    cell.hidesAccessoryWhenEditing = NO;
  }
#else
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier];

  if ( cell == nil ) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:kCellIdentifier] autorelease];
  }
  int row = indexPath.row;
  if ( self.editing )
    row--;
  if ( self.editing && row == -1 ) {
    cell.text = @"Add new tunebook";
  } else {
    Playlist *playlist = (Playlist *)[data objectAtIndex:row];

    cell.text = playlist.name;
    if ( playlist.type == kPlaylistTypeSearch )
      cell.accessoryView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"smartbook.png"]];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    static float version = 0;
    if ( version == 0 )
      version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if ( version >= 3.0 )
      cell.editingAccessoryType = UITableViewCellAccessoryDetailDisclosureButton;
    cell.hidesAccessoryWhenEditing = NO;
  }

#endif

	return cell;
}

- (UITableViewCell *)tableviewCellWithReuseIdentifier:(NSString *)identifier {
	
  CGRect bounds = [tableView bounds];
	CGRect rect = CGRectMake(0.0, 0.0, bounds.size.width, 34);
	
	UITableViewCell *cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:identifier] autorelease];
		
	rect = CGRectMake( 6, 13, 16, 16 );
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:rect];
	imageView.tag = kIconTag;
  imageView.opaque = NO;
	[cell.contentView addSubview:imageView];
	[imageView release];
	
	rect = CGRectMake( 28, 3, bounds.size.width-60, 34);
	UILabel *label = [[UILabel alloc] initWithFrame:rect];
	label.tag = kNameTag;
	label.font = [UIFont boldSystemFontOfSize:20];
	label.adjustsFontSizeToFitWidth = NO;
  label.opaque = NO;
	[cell.contentView addSubview:label];
	label.highlightedTextColor = [UIColor whiteColor];
	[label release];
	return cell;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tv editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
  if ( self.editing ) {
    if ( indexPath.row == 0 ) {
        return UITableViewCellEditingStyleInsert;
    } else {
        return UITableViewCellEditingStyleDelete;
    }
  }
  return UITableViewCellEditingStyleNone;
}

- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
  if (editingStyle == UITableViewCellEditingStyleDelete) {
    int row = indexPath.row;
    if ( self.editing )
      row--;
    if ( row < [data count] ) {
      Playlist *playlist = (Playlist *)[data objectAtIndex:row];
      [playlist deleteFromDatabase];
      [data removeObjectAtIndex:row];
    }
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
  } else if (editingStyle == UITableViewCellEditingStyleInsert) {
    Playlist *playlist = [[Playlist alloc] init];
    playlist.name = @"New Tunebook";
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate addPlaylist:playlist];
    [tableView reloadData];
    detailsController.playlist = playlist;
    detailsController.tableView = tv;
    detailsController.indexPath = indexPath;
#if TARGET_IPAD
    detailsController.contentSizeForViewInPopover = CGSizeMake(320,480);
    [[self navigationController] pushViewController:detailsController animated:YES];
#else
    [appDelegate.navigationController pushViewController:detailsController animated:YES];
#endif
  }
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
  return indexPath.row != 0 && indexPath.row <= [data count];
}

- (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath
{
  // Check for moving to the placeholder row. If so, retarget to just below that row.
  if ( proposedDestinationIndexPath.row == 0 )
    return [NSIndexPath indexPathForRow:1 inSection:sourceIndexPath.section];

  return proposedDestinationIndexPath;
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
  if ( toIndexPath.row <= [data count] ) {
    id item = [[data objectAtIndex:fromIndexPath.row-1] retain];
    [data removeObject:item];
    [data insertObject:item atIndex:toIndexPath.row-1];
    [item release];
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [appDelegate.database updateTunebookSortOrder];
  }
}

- (void)addTunebook:(id)sender
{
  Playlist *playlist = [[Playlist alloc] init];
  playlist.name = @"New Tunebook";
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [appDelegate addPlaylist:playlist];
  [tableView reloadData];
  detailsController.playlist = playlist;
  detailsController.tableView = tableView;
  detailsController.indexPath = [NSIndexPath indexPathForRow:[data count]-1 inSection:0];
#if TARGET_IPAD
  detailsController.contentSizeForViewInPopover = CGSizeMake(320,480);
  [[self navigationController] pushViewController:detailsController animated:YES];
#else
  [appDelegate.navigationController pushViewController:detailsController animated:YES];
#endif
}

@end



@implementation PlaylistDetailsController

@synthesize tableView, indexPath;

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

- (Playlist*)playlist
{
  return playlist;
}

- (void)setPlaylist:(Playlist*)p
{
	playlist = p;
  [self.tableView reloadData];
}

- (void)viewDidLoad
{	
  [super viewDidLoad];
  self.tableView.scrollsToTop = NO;
}

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

- (void)viewWillDisappear:(BOOL)animated
{
  [textField resignFirstResponder];
  if ( ![playlist.name isEqualToString:textField.text] ) {
    [playlist updateName:textField.text];
#if TARGET_IPAD
    NSArray* indexPaths = [NSArray arrayWithObject:indexPath];
    [tableView reloadRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
#else
    [[NSNotificationCenter defaultCenter] postNotificationName:@"playlistsChanged" object:self];
#endif
  }
}

#pragma mark UITableViewDataSource

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

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  return @"Tunebook Name";
}

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

- (UITableViewCell *)tableView:(UITableView *)tv cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  static NSString *kNameCellIdentifier = @"NameCell";

  EditTextTableCell* cell = (EditTextTableCell*)[tv dequeueReusableCellWithIdentifier:kNameCellIdentifier];
  if ( cell == nil ) {
    CGRect rect;
    rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
    cell = [[[EditTextTableCell alloc] initWithFrame:rect reuseIdentifier:kNameCellIdentifier] autorelease];
    cell.textField.returnKeyType = UIReturnKeyDone;
    cell.textField.delegate = self;
    [cell.textField becomeFirstResponder];
  }
  cell.textField.text = playlist.name;
//  [cell.textField selectAll:nil];
  textField = cell.textField;

  return cell;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
#if 1//FIXME - new way of creating tunebooks: go straight to playlist and start adding tunes
//  [tv deselectRowAtIndexPath:indexPath animated:YES];
//  [self setEditing:NO animated:NO];
//  [self viewWillDisappear:false]; // Hide the Edit button
  MainViewController *controller = [[MainViewController alloc] initWithNibName:@"MainView" bundle:nil];
  controller.playlist = playlist;
  UINavigationController *navigationController = self.navigationController;
  [navigationController popViewControllerAnimated:NO];
  [navigationController pushViewController:controller animated:YES];

  MainViewController *addTunesController = [[MainViewController alloc] initWithNibName:@"AddTunes" bundle:nil];
  addTunesController.playlist = nil;
  addTunesController.choosingTunes = playlist;
#if TARGET_IPAD
  addTunesController.modalPresentationStyle = UIModalPresentationFormSheet;
#endif
  [self presentModalViewController:addTunesController animated:YES];
  [controller.tableView reloadData];
#else
  [self.navigationController popViewControllerAnimated:YES];
#endif
  return true;
}

@end

