#import "HTTPTuneResponse.h"

@implementation HTTPTuneResponse

@synthesize httpHeaders;

- (id)initWithTunes:(NSArray *)t
{
  self = [super init];
  if ( self ) {
    tunes = [t retain];
    currentIndex = -1;
    currentOffset = -1;
  }
  return self;
}

- (void)dealloc
{
  [tunes release];
  if ( currentDots )
    [currentDots release];
  [super dealloc];
}

- (UInt64)offset
{
  return 0;//FIXME
}

- (void)setOffset:(UInt64)offset
{
  //FIXME
}

- (NSData *)readDataOfLength:(unsigned int)length
{
  NSMutableData* data = [[NSMutableData alloc] init];
  while ( length > 0 ) {
    if ( currentOffset == -1 ) {
      currentIndex++;
      if ( currentIndex >= [tunes count] )
        break;
      currentOffset = 0;
      Tune* tune = [tunes objectAtIndex:currentIndex];
      BOOL hydrated = tune.hydrated;
      if ( !hydrated )
        [tune hydrate];
      if ( currentDots )
        [currentDots release];
      NSString* dots = [[tune dots] stringByReplacingOccurrencesOfString:@"X:1" withString:[NSString stringWithFormat:@"X:%d", currentIndex+1]];
//      dots = [dots stringByAppendingString:@"\n"];
      currentDots = [[dots dataUsingEncoding:NSUTF8StringEncoding] retain];
      if ( !hydrated )
        [tune dehydrate];
    }
    NSInteger count = MIN( length, (int)currentDots.length-currentOffset+1 );
    if ( count > 0 ) {
      count = MIN( length, (int)currentDots.length-currentOffset );
      [data appendData:[currentDots subdataWithRange:NSMakeRange(currentOffset, count)]];
      currentOffset += count;
      if ( currentOffset >= currentDots.length ) {
        currentOffset = -1;
        [data appendBytes:"\n" length:1];
      }
    } else
      currentOffset = -1;
    length -= count;
  }
  [data autorelease];
  return data;
}

// Should only return YES after the HTTPConnection has read all available data.
- (BOOL)isDone
{
  return currentIndex >= [tunes count] && currentOffset == -1;
}

- (BOOL)isChunked
{
  return YES;
}

- (UInt64)contentLength
{
  return 0;
}

@end
