//
//  RecordingPreviewPictureHandler.m
//  CyTV
//
//  Created by Andreas Junghans on 06.01.08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "RecordingPreviewPictureHandler.h"
#import "RecordingInfo.h"
#import "GUIFileHandler.h"
#import "HTTPServer.h"

// TODO: support caching


@implementation RecordingPreviewPictureHandler

- (void)handleRequest {
    NSString *idString = [_paramsDict objectForKey:@"id"];
    UInt64 idNumber;
    if (idString != nil) {
        NSScanner *idScanner = [NSScanner scannerWithString:idString];
        if (![idScanner scanLongLong:(long long *)&idNumber]) {
            idString = nil;
        }
    }
    if (idString != nil) {
        NSData *previewPNG = [RecordingInfo getPreviewPNGForId:idNumber];
        if (previewPNG != nil) {
            CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, 200, NULL, kCFHTTPVersion1_1);
            unsigned long long contentLength = [previewPNG length];
            NSString *contentLengthString = [[NSNumber numberWithUnsignedLongLong:contentLength] stringValue];
            CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (CFStringRef)contentLengthString);
            CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("image/png"));
            NSData *responseData = [(NSData *)CFHTTPMessageCopySerializedMessage(response) autorelease];
            [_asyncSocket writeData:responseData withTimeout:WRITE_BODY_TIMEOUT tag:HTTP_PARTIAL_RESPONSE];
            [_asyncSocket writeData:previewPNG withTimeout:WRITE_BODY_TIMEOUT tag:HTTP_RESPONSE];
            return;
        }
    }
    [GUIFileHandler writeFileForPath:@"/nopreview.png" contentType:@"image/png" socket:_asyncSocket];
}

@end
