#import <QuartzCore/QuartzCore.h>
#import "TuneViewController.h"
#import "TuneView.h"
#import "Tune.h"

@implementation TuneView

@synthesize delegate, scale, tune, numPages;

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

-(void)drawRect:(CGRect)rect
{
  CGRect bounds = self.bounds;
  CGContextRef context = UIGraphicsGetCurrentContext();

  CGContextSetRGBFillColor( context, 1.0, 1.0, 1.0, 1.0 );
  CGContextFillRect( context, bounds );

  if ( tune ) {
    CGContextSetLineWidth( context, 1.0f );
    CGContextTranslateCTM( context, 0.0, bounds.size.height );
    CGContextScaleCTM( context, 1.0, -1.0 );

    CGContextTranslateCTM( context, 0.0, bounds.size.height-PaperHeight*scale ); // Translate to one page from the top
    CGContextScaleCTM( context, scale, scale );
    [Tune drawTune:tune intoContext:context bounds:bounds scale:self.scale];

    CGContextSetRGBFillColor( context, 0.9f, 0.9f, 0.9f, 1.0 );
    for ( int y = PaperHeight; y < bounds.size.height/scale+1; y += PaperHeight ) {
      CGContextMoveToPoint( context, 0, y );
      CGContextAddLineToPoint( context, bounds.size.width/scale, y );
    }
    CGContextStrokePath( context );
  }
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
  [delegate touchesBegan:touches withEvent:event];
}

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
  [delegate touchesMoved:touches withEvent:event];
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
  [delegate touchesEnded:touches withEvent:event];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
  [delegate touchesCancelled:touches withEvent:event];
}

- (void)removeMeFromParent:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
  [self removeFromSuperview];
}
@end
