/*
SRPredictEncoding.m

Author: Hiroyuki Yamashita

Copyright 2004 The Shiira Project. All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted 
provided that the following conditions are met:

  1. Redistributions of source code must retain the above copyright notice, this list of conditions 
  and the following disclaimer.

  2. Redistributions in binary form must reproduce the above copyright notice, this list of 
  conditions and the following disclaimer in the documentation and/or other materials provided 
  with the distribution.

THIS SOFTWARE IS PROVIDED BY THE SHIIRA PROJECT ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, 
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE SHIIRA PROJECT OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/

#import "SRPredictEncoding.h"

#import "WebKitEx.h"

@implementation SRPredictEncoding

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

- (id)initWithTemplateURL:(NSString *)templateURL;
{
    NSString *URLString;
    NSURL *URL;
    NSURLRequest *request;
    NSHTTPURLResponse *response;
    NSData *data;
    NSError *error;

    if (!(self = [super init]))
        return self;

    URLString = [NSString stringWithFormat:templateURL,@"Shiira"];
    URL = [NSURL _web_URLWithUserTypedString:URLString];
    request = [NSURLRequest requestWithURL:URL];
    data = [NSURLConnection sendSynchronousRequest:request
                            returningResponse:&response
                            error:&error];
    if (!error && [response statusCode] == 200) {
        _textEncodingName = [[response textEncodingName] retain];
        _data = [data retain];
    }

    return self;
}

- (NSString *)textEncodingName
{
    NSXMLParser *parser;

    if (_textEncodingName)
        return _textEncodingName;

    if (_data) {
        parser = [[[NSXMLParser alloc] initWithData:_data] autorelease];
        [parser setDelegate:self];
        [parser parse];
    }

    return _textEncodingName;
}

- (NSStringEncoding)textEncoding
{
    CFStringEncoding encoding;

    [self textEncodingName];
    if (!_textEncodingName)
        return 0;

    if ([_textEncodingName caseInsensitiveCompare:@"shift_jis"] == NSOrderedSame)
        return NSShiftJISStringEncoding;
    encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)_textEncodingName);

    return CFStringConvertEncodingToNSStringEncoding(encoding);
}

// NSXMLParser delegate
- (void)parser:(NSXMLParser *)parser
    didStartElement:(NSString *)elementName
    namespaceURI:(NSString *)namespaceURI
    qualifiedName:(NSString *)qName
    attributes:(NSDictionary *)attributeDict
{
    NSEnumerator *enumerator;
    NSString *key;
    NSString *httpEquiv, *contentType;
    NSRange range;

    if ([elementName caseInsensitiveCompare:@"meta"] != NSOrderedSame)
        return;

    enumerator = [attributeDict keyEnumerator];
    httpEquiv = contentType = nil;
    while ((key = [enumerator nextObject]) != nil) {
        if ([key caseInsensitiveCompare:@"http-equiv"] == NSOrderedSame)
            httpEquiv = [attributeDict valueForKey:key];
        if ([key caseInsensitiveCompare:@"content"] == NSOrderedSame)
            contentType = [attributeDict valueForKey:key];
    }
    if (!httpEquiv || !contentType)
        return;
    if ([httpEquiv caseInsensitiveCompare:@"content-type"] != NSOrderedSame)
	return;

    range = [contentType rangeOfString:@"charset=" options:NSCaseInsensitiveSearch];
    range.location = NSMaxRange(range);
    range.length = [contentType length] - range.location;
    if (NSLocationInRange(range.location, NSMakeRange(0, [contentType length])))
	_textEncodingName = [[contentType substringWithRange:range] retain];
}

@end
