#import "SettingsController.h"
#import "AppDelegate.h"
#import "OnOffTableCell.h"
#import "SliderTableCell.h"

UIFont* gFonts[4];//FIXME

#if ABC_FONTS
@interface FontPickerController : UITableViewController {
  NSMutableArray* fontNames;
  NSInteger row;
}

@property (nonatomic) NSInteger row;
@end

@implementation FontPickerController
@synthesize row;

- (id)init {
	self = [super init];
	if ( self ) {
    fontNames = [[UIFont familyNames] sortedArrayUsingSelector:@selector(compare:)];
    [fontNames retain];
//    [fontNames sortUsingSelector:@selector(compare:)];
	}
	return self;
}

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

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

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"FontPickerCell"];
  if (cell == nil) {
    CGRect rect;
    rect = CGRectMake(0.0, 0.0, 300.0,32.0);
    cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:@"FontPickerCell"] autorelease];
  }
  cell.text = [fontNames objectAtIndex:indexPath.row];
  cell.font = [UIFont fontWithName:[fontNames objectAtIndex:indexPath.row] size:20];
  return cell;
}

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
  gFonts[row] = [UIFont fontWithName:[fontNames objectAtIndex:indexPath.row] size:20];
  [self.navigationController popViewControllerAnimated:YES];
}

@end
#endif

@interface SortTunesTableCell : UITableViewCell {
	UILabel *label;
	UISegmentedControl *control;
	NSString* notification;
}

@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UISegmentedControl *control;
@property (nonatomic, retain) NSString *notification;

@end

@implementation SortTunesTableCell

@synthesize label;
@synthesize control;
@synthesize notification;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
	self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
	if (self) {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    CGRect frame = CGRectMake(18.0, 44.0, 264.0, 32.0);
    control = [[UISegmentedControl alloc] initWithFrame:frame];
    [control insertSegmentWithTitle:@"Index" atIndex:0 animated:NO];
    [control insertSegmentWithTitle:@"Title" atIndex:1 animated:NO];
    [control insertSegmentWithTitle:@"Key" atIndex:2 animated:NO];
    [control insertSegmentWithTitle:@"Meter" atIndex:3 animated:NO];
    control.selectedSegmentIndex = appDelegate.tuneSortOrder;
    [control addTarget:self action:@selector(sortAction:) forControlEvents:UIControlEventValueChanged];
		[[self contentView] addSubview:control];
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 2.0, 150.0, 40.0)];
    label.backgroundColor = [UIColor clearColor];
		[[self contentView] addSubview:label];
		self.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	return self;
}

- (void)sortAction:(UISwitch*)c {
	[[NSNotificationCenter defaultCenter] postNotificationName:self.notification object:c];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
	[super setSelected:selected animated:animated];
}

@end

#if TARGET_IPAD
@interface TransitionsTableCell : UITableViewCell {
	UILabel *label;
	UISegmentedControl *control;
	NSString* notification;
}

@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UISegmentedControl *control;
@property (nonatomic, retain) NSString *notification;

@end

@implementation TransitionsTableCell

@synthesize label;
@synthesize control;
@synthesize notification;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
	self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
	if ( self ) {
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    CGRect frame = CGRectMake(18.0, 44.0, 264.0, 32.0);
    control = [[UISegmentedControl alloc] initWithFrame:frame];
    [control insertSegmentWithTitle:@"None" atIndex:0 animated:NO];
    [control insertSegmentWithTitle:@"Curl" atIndex:1 animated:NO];
    [control insertSegmentWithTitle:@"Slide" atIndex:2 animated:NO];
    [control insertSegmentWithTitle:@"Fade" atIndex:3 animated:NO];
    control.selectedSegmentIndex = appDelegate.tuneSortOrder;
    [control addTarget:self action:@selector(sortAction:) forControlEvents:UIControlEventValueChanged];
		[[self contentView] addSubview:control];
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 2.0, 150.0, 40.0)];
    label.backgroundColor = [UIColor clearColor];
		[[self contentView] addSubview:label];
		self.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	return self;
}

- (void)sortAction:(UISwitch*)c {
	[[NSNotificationCenter defaultCenter] postNotificationName:self.notification object:c];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
	[super setSelected:selected animated:animated];
}

@end


@interface FontTableCell : UITableViewCell<UIPickerViewDataSource, UIPickerViewDelegate> {
	UILabel *label;
	UIPickerView *control;
	NSString* notification;
  NSArray* fontNames;
}

@property (nonatomic, retain) UILabel *label;
@property (nonatomic, retain) UIPickerView *control;
@property (nonatomic, retain) NSString *notification;

@end

@implementation FontTableCell

@synthesize label;
@synthesize control;
@synthesize notification;

- (id)initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
	self = [super initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
	if ( self ) {
    fontNames = [UIFont familyNames];
    [fontNames retain];
    CGRect frame = CGRectMake(18.0, 44.0, 300.0, 32.0);
    control = [[UIPickerView alloc] initWithFrame:frame];
    [control setDelegate:self];
		[[self contentView] addSubview:control];
		
		label = [[UILabel alloc] initWithFrame:CGRectMake(20.0, 2.0, 150.0, 40.0)];
    label.backgroundColor = [UIColor clearColor];
		[[self contentView] addSubview:label];
		self.selectionStyle = UITableViewCellSelectionStyleNone;
	}
	return self;
}

#pragma mark UIPickerView delegate methods

- (int)numberOfComponentsInPickerView:(UIPickerView *)picker
{
  return 1;
}

- (int)pickerView:(UIPickerView *)picker numberOfRowsInComponent:(int)col
{
  return [fontNames count];
}

//- (int)rowForFont:(NSString *)fontName
//{
//  int count = [fontNames count];
//  for (int i = 0; i < count; i++)
//    if ([[fontNames objectAtIndex:i] isEqualToString:fontName])
//      return i;
//  return 0;
//}

#pragma mark UIPickerView delegate methods

//- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
//{
//  return 40.0f;
//}

//- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component
//{
//  return 20.0f;
//}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
  return [fontNames objectAtIndex:row];
}


@end
#endif

#define kViewTag				1		// for tagging our embedded controls for removal at cell recycle time

enum {
  kTunesSection,
  kPlayerSection,
  kViewSection,
#if ABC_FONTS
  kMusicSection,
#endif
  kOtherSection,
};

@implementation SettingsController

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

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

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

- (void)viewWillAppear:(BOOL)animated
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  sortOrder = appDelegate.tuneSortOrder;
}

- (void)viewWillDisappear:(BOOL)animated
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  if ( sortOrder != appDelegate.tuneSortOrder ) {
    appDelegate.tuneSortOrder = sortOrder;
    [appDelegate sortTunes];
  }
}

- (CGSize)contentSizeForViewInPopoverView {
  return CGSizeMake(320.0, 440.0);
}

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
#if ABC_FONTS
  return 4;
#endif
  return 3;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
  switch ( section ) {
  case kTunesSection:
    return @"General";
  case kPlayerSection:
    return @"Player";
  case kViewSection:
    return @"View";
#if ABC_FONTS
  case kMusicSection:
    return @"Music";
#endif
	}
  return @"Other";
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
  switch ( section ) {
  case kTunesSection:
    return 2;
  case kPlayerSection:
    return 2;
  case kViewSection:
#if TARGET_IPAD
    return 2;
#else
    return 1;
#endif
#if ABC_FONTS
  case kMusicSection:
    return 4;
#endif
	}
  return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
#if TARGET_IPAD
	if (indexPath.section == kViewSection ) {
    if (  indexPath.row == 0 )
      return 90.0;
    else
      return 75.0;
  }
#else
	if (indexPath.section == kViewSection && indexPath.row == 0 )
    return 70.0;
#endif
	return (indexPath.section == kTunesSection && indexPath.row == 0) ? 90.0 : 44.0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

	if ( indexPath.section == kPlayerSection) {
		OnOffTableCell* cell = (OnOffTableCell*)[tableView dequeueReusableCellWithIdentifier:@"OnOffCell"];
		if ( cell == nil ) {
			CGRect rect;
			rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
			cell = [[[OnOffTableCell alloc] initWithFrame:rect reuseIdentifier:@"OnOffCell"] autorelease];
      [cell.switchControl removeTarget:self action:nil forControlEvents:UIControlEventValueChanged];
			if ( indexPath.row == 0 ) {
        cell.label.text = @"Guitar Chords";
        cell.switchControl.on = appDelegate.guitarChords;
        [cell.switchControl addTarget:self action:@selector(guitarChordsAction:) forControlEvents:UIControlEventValueChanged];
      } else {
        cell.label.text = @"Loop Playback";
        cell.switchControl.on = appDelegate.loopPlayback;
        [cell.switchControl addTarget:self action:@selector(loopPlaybackAction:) forControlEvents:UIControlEventValueChanged];
      }
    }
		return cell;
	} else if ( indexPath.section == kViewSection) {
#if TARGET_IPAD
    if ( indexPath.row == 0 ) {
      TransitionsTableCell* cell = (TransitionsTableCell*)[tableView dequeueReusableCellWithIdentifier:@"TransitionsCell"];
      if ( cell == nil ) {
        CGRect rect;
        rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
        cell = [[[TransitionsTableCell alloc] initWithFrame:rect reuseIdentifier:@"TransitionsCell"] autorelease];
        cell.label.text = @"Transitions";
        cell.control.selectedSegmentIndex = appDelegate.transitionType;
        [cell.control addTarget:self action:@selector(transitionAction:) forControlEvents:UIControlEventValueChanged];
      }
      return cell;
    } else if ( indexPath.row == 1 ) {
#else
    if ( indexPath.row == 0 ) {
#endif
      SliderTableCell* cell = (SliderTableCell*)[tableView dequeueReusableCellWithIdentifier:@"SliderTableCell"];
      if ( cell == nil ) {
        CGRect rect;
        rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
        cell = [[[SliderTableCell alloc] initWithFrame:rect reuseIdentifier:@"SliderTableCell"] autorelease];
        cell.label.text = @"Note Scaling";
        cell.slider.minimumValue = 1.0f;
        cell.slider.maximumValue = 2.0f;
        cell.slider.value = appDelegate.tuneScaling;
        [cell.slider addTarget:self action:@selector(tuneScalingAction:) forControlEvents:UIControlEventValueChanged];
      }
      return cell;
    }
	} else if ( indexPath.section == kTunesSection) {
    if ( indexPath.row == 0 ) {
      SortTunesTableCell* cell = (SortTunesTableCell*)[tableView dequeueReusableCellWithIdentifier:@"SortTunesCell"];
      if ( cell == nil ) {
        CGRect rect;
        rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
        cell = [[[SortTunesTableCell alloc] initWithFrame:rect reuseIdentifier:@"SortTunesCell"] autorelease];
        cell.label.text = @"Sort Tunes by";
        cell.control.selectedSegmentIndex = appDelegate.tuneSortOrder;
        [cell.control addTarget:self action:@selector(sortAction:) forControlEvents:UIControlEventValueChanged];
      }
      return cell;
    } else {
      OnOffTableCell* cell = (OnOffTableCell*)[tableView dequeueReusableCellWithIdentifier:@"OnOffCell"];
      if ( cell == nil ) {
        CGRect rect;
        rect = CGRectMake(0.0, 0.0, 320.0, 60.0);
        cell = [[[OnOffTableCell alloc] initWithFrame:rect reuseIdentifier:@"OnOffCell"] autorelease];
        cell.label.text = @"Prevent Sleep";
        cell.switchControl.on = appDelegate.preventSleep;
        [cell.switchControl addTarget:self action:@selector(preventSleepAction:) forControlEvents:UIControlEventValueChanged];
      }
      return cell;
    }
    return nil;
#if ABC_FONTS
	} else if ( indexPath.section == kMusicSection) {
		UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"FontCell"];
		if (cell == nil) {
			CGRect rect;
			rect = CGRectMake(0.0, 0.0, 300.0, 160.0);
			cell = [[[UITableViewCell alloc] initWithFrame:rect reuseIdentifier:@"FontCell"] autorelease];
      switch ( indexPath.row ) {
      case 0:
        cell.text = @"Title Font";
        break;
      case 1:
        cell.text = @"Subtitle Font";
        break;
      case 2:
        cell.text = @"Composer Font";
        break;
      case 3:
        cell.text = @"Words Font";
        break;
      }
		}
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
		return cell;
#endif
  }

  return nil;
}

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
#if ABC_FONTS
  [tv deselectRowAtIndexPath:indexPath animated:YES];
	if (indexPath.section == kMusicSection && indexPath.row < 4) {
    FontPickerController *controller = [[FontPickerController alloc] init];
    controller.row = indexPath.row;
    [[self navigationController] pushViewController:controller animated:YES];
  }
#endif
}

- (IBAction)sortAction:(id)sender
{
  UISegmentedControl *control = (UISegmentedControl *)sender;
  sortOrder = control.selectedSegmentIndex;
}

- (IBAction)guitarChordsAction:(id)sender
{
  UISwitch *control = (UISwitch *)sender;
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.guitarChords = control.on;
}

- (IBAction)loopPlaybackAction:(id)sender
{
  UISwitch *control = (UISwitch *)sender;
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.loopPlayback = control.on;
}

- (IBAction)preventSleepAction:(id)sender
{
  UISwitch *control = (UISwitch *)sender;
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.preventSleep = control.on;
  [UIApplication sharedApplication].idleTimerDisabled = appDelegate.preventSleep;
}

#if TARGET_IPAD
- (IBAction)transitionAction:(id)sender
{
  UISegmentedControl *control = (UISegmentedControl *)sender;
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.transitionType = control.selectedSegmentIndex;
}
#endif

- (IBAction)tuneScalingAction:(id)sender
{
  UISlider *control = (UISlider *)sender;
  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  appDelegate.tuneScaling = control.value;
  [[NSNotificationCenter defaultCenter] postNotificationName:@"musicPreferencesChanged" object:self]; 
}

@end

