//
//  ResponseHandler.m
//  CyTV
//
//  Created by Andreas Junghans on 29.12.07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "ResponseHandler.h"
#import "HTTPServer.h"


@implementation ResponseHandler

- (void)setRequest:(CFHTTPMessageRef)request {
    if (_request && _request != request) {
        CFRelease(_request);
    }
    _request = request;
    if (_request) {
        CFRetain(_request);
    }
}

- (void)setURI:(NSURL *)uri {
    [_uri autorelease];
    _uri = [uri retain];
}

- (void)setMethod:(NSString *)method {
    [_method autorelease];
    _method = [method retain];
}

- (void)setPath:(NSString *)path {
    [_path autorelease];
    _path = [path retain];
}

- (void)setQuery:(NSString *)query {
    [_query autorelease];
    _query = [query retain];
}

- (void)setParamsDict:(NSDictionary *)paramsDict {
    [_paramsDict autorelease];
    _paramsDict = [paramsDict retain];
}

- (void)setAsyncSocket:(AsyncSocket *)asyncSocket {
    [_asyncSocket autorelease];
    _asyncSocket = [asyncSocket retain];
}

- (void)dealloc {
    if (_request) {
        CFRelease(_request);
    }
    [_uri release];
    [_method release];
    [_path release];
    [_query release];
    [_paramsDict release];
    [_asyncSocket release];
    [super dealloc];
}

- (void)handleRequest {
}

- (void)onSocketCanWrite:(AsyncSocket *)sock {
}

- (void)shutDownAndRelease {
    [self release];
}

+ (void)writeResponseWithCode:(int)statusCode content:(NSString *)content socket:(AsyncSocket *)socket timeout:(NSTimeInterval)timeout {
    CFHTTPMessageRef response = CFHTTPMessageCreateResponse(kCFAllocatorDefault, statusCode, NULL, kCFHTTPVersion1_1);
    if (content != nil && [content length] > 0) {
        const char *contentUTF8 = [content UTF8String];
        size_t contentLength = strlen(contentUTF8);
        NSData *contentData = [NSData dataWithBytes:contentUTF8 length:contentLength];
        NSString *contentLengthString = [[NSNumber numberWithUnsignedLongLong:contentLength] stringValue];
        CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), (CFStringRef)contentLengthString);
        CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Type"), CFSTR("text/plain;charset=utf-8"));
        CFHTTPMessageSetBody(response, (CFDataRef)contentData);
    } else {
        CFHTTPMessageSetHeaderFieldValue(response, CFSTR("Content-Length"), CFSTR("0"));
    }
    NSData *responseData = [(NSData *)CFHTTPMessageCopySerializedMessage(response) autorelease];
    [socket writeData:responseData withTimeout:timeout tag:HTTP_RESPONSE];
    CFRelease(response);
}

@end
