#import "TuneSettingsController.h"
#import "AppDelegate.h"
#import "TunePlayer.h"
#import <math.h>

@implementation TuneSettingsView

- (void)fillRoundedRect:(CGRect)rect inContext:(CGContextRef)context
{
  float radius = 8;

  CGContextBeginPath(context);
  CGContextSetGrayFillColor(context, 0.1, 0.8);
  CGContextMoveToPoint(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect));
  CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMinY(rect) + radius, radius, 3 * M_PI / 2, 0, 0);
  CGContextAddArc(context, CGRectGetMaxX(rect) - radius, CGRectGetMaxY(rect) - radius, radius, 0, M_PI / 2, 0);
  CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMaxY(rect) - radius, radius, M_PI / 2, M_PI, 0);
  CGContextAddArc(context, CGRectGetMinX(rect) + radius, CGRectGetMinY(rect) + radius, radius, M_PI, 3 * M_PI / 2, 0);

  CGContextClosePath(context);
  CGContextFillPath(context);
}

- (void)drawRect:(CGRect)rect
{
	CGRect boxRect = self.bounds;
  CGContextRef ctxt = UIGraphicsGetCurrentContext();	
	boxRect = CGRectInset(boxRect, 1.0f, 1.0f);
  [self fillRoundedRect:boxRect inContext:ctxt];
}

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

@end

@implementation TuneSettingsController

@synthesize speedSlider, pitchSlider, volumeSlider;
@synthesize player;

- (id)initWithPlayer:(TunePlayer *)tunePlayer
{
  self = [[TuneSettingsController alloc] initWithNibName:@"TuneSettings" bundle:nil];
  if ( self ) {
    self.player = tunePlayer;
  }
  return self;
}

- (void)viewDidLoad
{
  instrumentButtons[0] = instrument1Button;
  instrumentButtons[1] = instrument2Button;
  instrumentButtons[2] = instrument3Button;
  instrumentButtons[3] = instrument4Button;
  instrumentButtons[4] = instrument5Button;
  instrumentButtons[5] = instrument6Button;
  instrumentButtons[6] = instrument7Button;
  instrumentButtons[7] = instrument8Button;
  self.view.backgroundColor = [UIColor clearColor];

  speedSlider.value = player.speed;
  volumeSlider.value = player.volume;
  currentInstrument = player.voice;
  for ( int i = 0; i < 8; i++ ) {
    UIButton *b = instrumentButtons[i];
    [b setSelected:i == currentInstrument];
  }
}

- (IBAction)donePressed:(id)sender
{
  [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)speedChanged:(id)sender
{
  [player setSpeed:[speedSlider value]];
}

- (IBAction)pitchChanged:(id)sender
{
  player.transpose = (int)([pitchSlider value] * 127) - 64;
}

- (IBAction)volumeChanged:(id)sender
{
  player.volume = [volumeSlider value];
}

- (IBAction)instrumentChanged:(id)sender
{
  for ( int i = 0; i < 8; i++ ) {
    UIButton *b = instrumentButtons[i];
    if ( b == sender ) {
      [b setSelected:YES];
      [player setVoice:i];
    } else {
      [b setSelected:NO];
    }
  }
}

@end
