/*
SRIconDatabase.m

Author: Makoto Kinoshita

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 "SRBookmarkIconDatabase.h"

#import "WebKitEx.h"

NSString*   SRFaviconAddedNotification = @"SRFaviconAddedNotification";

@implementation SRBookmarkIconDatabase

//--------------------------------------------------------------//
#pragma mark -- Initialzie --
//--------------------------------------------------------------//

+ (SRBookmarkIconDatabase*)sharedInstance
{
    static SRBookmarkIconDatabase*  _instance = nil;
    if (!_instance) {
        _instance = [[SRBookmarkIconDatabase alloc] init];
    }
    
    return _instance;
}

- (id)init
{
    self = [super init];
    if (!self) {
        return self;
    }
    
    // Initialize instance variables
    _faviconDict = [[NSMutableDictionary dictionary] retain];
    _iconURLDict = [[NSMutableDictionary dictionary] retain];
    _connectionDict = [[NSMutableDictionary dictionary] retain];
    _connections = [[NSMutableArray array] retain];
    
    return self;
}

- (void)dealloc
{
    [_faviconDict release];
    [_iconURLDict release];
    [_connectionDict release];
    [_connections release];
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Icon management --
//--------------------------------------------------------------//

- (NSImage*)defaultIcon
{
    static NSImage* _defaultIcon = nil;
    if (!_defaultIcon) {
        _defaultIcon = [[[WebIconDatabase sharedIconDatabase] 
                defaultIconWithSize:NSMakeSize(16, 16)] copy];
        [_defaultIcon retain];
    }
    
    return _defaultIcon;
}

- (NSImage*)iconOrDefaultIconForURLString:(NSString*)URLString
{
    NSImage*    icon = nil;
    
    // Try raw URL string
    icon = [self iconForFaviconURLString:URLString];
    if (!icon) {
        // Get favicon URL string
        NSString*   faviconURLString;
        faviconURLString = [[WebIconDatabase sharedIconDatabase] iconURLOfURL:URLString];
        if (faviconURLString) {
            // Get favicon
            icon = [self iconForFaviconURLString:faviconURLString];
        }
    }
    
    // Validate icon
    if (!icon || ![icon isValid] || NSEqualSizes([icon size], NSZeroSize)) {
        icon = [self defaultIcon];
    }
    
    return icon;
}

- (NSImage*)iconForFaviconURLString:(NSString*)faviconURLString
{
    return [_faviconDict objectForKey:faviconURLString]; 
}

- (NSDictionary*)allFavicons
{
    return _faviconDict;
}

- (void)loadFaviconURLString:(NSString*)faviconURLString
{
    // Load favicon
    NSURLRequest*       request;
    NSURLConnection*    connection;
    request = [NSURLRequest requestWithURL:[NSURL URLWithString:faviconURLString]];
    connection = [NSURLConnection connectionWithRequest:request delegate:self];
    
    [_connections addObject:connection];
    
    NSDictionary*   connectInfo;
    connectInfo = [NSDictionary dictionaryWithObjectsAndKeys:
            faviconURLString, @"URLString", 
            [NSMutableData data], @"data", 
            nil];
    [_connectionDict 
            setObject:connectInfo 
            forKey:[NSNumber numberWithUnsignedInt:(unsigned int)connection]];
}

- (void)registerIcon:(NSImage*)icon forURLString:(NSString*)URLString
{
    if (!icon || !URLString) {
        return;
    }
    
    // Create image
    NSImage*    image;
    image = [icon copy];
    if (!image || ![image isValid] || NSEqualSizes([image size], NSZeroSize)) {
        return;
    }
    [image setScalesWhenResized:YES];
    [image setSize:NSMakeSize(16, 16)];
    
    // Register icon
    [_faviconDict setObject:image forKey:URLString];
    
    // Notify it
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRFaviconAddedNotification object:URLString];
}

//--------------------------------------------------------------//
#pragma mark -- NSURLConnection delegate --
//--------------------------------------------------------------//

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data
{
    // Append data
    NSDictionary*   connectInfo;
    NSMutableData*  loadingData;
    connectInfo = [_connectionDict objectForKey:[NSNumber numberWithUnsignedInt:(unsigned int)connection]];
    loadingData = [connectInfo objectForKey:@"data"];
    if (!loadingData) {
        return;
    }
    
    [loadingData appendData:data];
}

- (void)_removeConnection:(NSURLConnection*)connection
{
    [_connections removeObject:connection];
    [_connectionDict removeObjectForKey:[NSNumber numberWithUnsignedInt:(unsigned int)connection]];
}

- (void)connection:(NSURLConnection*)connection didFailWithError:(NSError*)error
{
    [self _removeConnection:connection];
}

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    // Get received data
    NSDictionary*   connectInfo;
    NSMutableData*  data;
    connectInfo = [_connectionDict objectForKey:[NSNumber numberWithUnsignedInt:(unsigned int)connection]];
    data = [connectInfo objectForKey:@"data"];
    if (!data) {
        [self _removeConnection:connection];
        return;
    }
    
    // Create image
    NSImage*    image;
    image = [[NSImage alloc] initWithData:data];
    [image autorelease];
    if (!image || ![image isValid] || NSEqualSizes([image size], NSZeroSize)) {
        [self _removeConnection:connection];
        return;
    }
    [image setScalesWhenResized:YES];
    [image setSize:NSMakeSize(16, 16)];
    
    // Get request
    NSString*   faviconURLString;
    faviconURLString = [connectInfo objectForKey:@"URLString"];
    if (faviconURLString) {
        [_faviconDict setObject:image forKey:faviconURLString];
        
        // Notify it
        [[NSNotificationCenter defaultCenter] 
                postNotificationName:SRFaviconAddedNotification object:faviconURLString];
    }
    
    // Remove connections
    [self _removeConnection:connection];
}

//--------------------------------------------------------------//
#pragma mark -- Persistence --
//--------------------------------------------------------------//

- (BOOL)loadFromFile:(NSString*)file
{
    // Unarchive file
    id  faviconDict;
    faviconDict = [NSUnarchiver unarchiveObjectWithFile:file];
    if (!faviconDict) {
        return NO;
    }
    
    [_faviconDict release];
    _faviconDict = [faviconDict retain];
    
    return YES;
}

- (BOOL)saveToFile:(NSString*)file
{
    // Archive icon dictionary
    return [NSArchiver archiveRootObject:_faviconDict toFile:file];
}

@end
