/*
SRVisualHistoryStorage.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 "SRAppDelegate.h"
#import "SRMainWindowController.h"
#import "SRVisualHistoryStorage.h"

#import "SRTabView.h"

// Notifications
NSString*   SRVisulaHistoryProgressStartedNotification = @"SRVisulaHistoryProgressStartedNotification";
NSString*   SRVisulaHistoryProgressEstimateChangedNotification = @"SRVisulaHistoryProgressEstimateChangedNotification";
NSString*   SRVisulaHistoryProgressFinishedNotification = @"SRVisulaHistoryProgressFinishedNotification";

//float  SRVisualHistoryMaxImageSizeWidth = 240.0f;
//float  SRVisualHistoryMaxImageSizeHeight = 180.0f;
float       SRVisualHistoryMaxImageSizeWidth = 480.0f;
float       SRVisualHistoryMaxImageSizeHeight = 360.0f;

@implementation SRVisualHistoryStorage

//--------------------------------------------------------------//
#pragma --  Initialize --
//--------------------------------------------------------------//

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

- (id)init
{
    self = [super init];
    if (!self) {
        return nil;
    }
    
    // Initialize member variables
    _loadingWebViews = [[NSMutableSet set] retain];
    
    // Register notifications
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self 
            selector:@selector(webViewProgressStarted:) 
            name:WebViewProgressStartedNotification 
            object:nil];
    [center addObserver:self 
            selector:@selector(webViewProgressEstimateChanged:) 
            name:WebViewProgressEstimateChangedNotification 
            object:nil];
    [center addObserver:self 
            selector:@selector(webViewProgressFinished:) 
            name:WebViewProgressFinishedNotification 
            object:nil];
    
    return self;
}

//--------------------------------------------------------------//
#pragma mark --  Visual history management --
//--------------------------------------------------------------//

- (NSString*)_filePathForFileName:(NSString*)fileName
{
    NSFileManager*	fileMgr;
    fileMgr = [NSFileManager defaultManager];
    
    // Get library path
    NSString*   filePath;
    filePath = [[NSApp delegate] libraryFolder];
    filePath = [filePath stringByAppendingPathComponent:@"History"];
    
    if (![fileMgr fileExistsAtPath:filePath]) {
        // Create directory
        [fileMgr createDirectoryAtPath:filePath attributes:nil];
    }
    
    filePath = [filePath stringByAppendingPathComponent:fileName];
    return filePath;
}

- (NSString*)_fileNameForWebView:(WebView*)webView
{
    NSString*   URLString;
    URLString = [[[[[webView mainFrame] dataSource] request] URL] absoluteString];
    if (!URLString) {
        URLString = @"visualHistory";
    }
    
    return [NSString stringWithFormat:@"%u.jpg", [URLString hash]];
}

- (NSString*)_fileNameForWebHistoryItem:(WebHistoryItem*)historyItem
{
    NSString*   URLString;
    URLString = [historyItem URLString];
    if (!URLString) {
        URLString = @"visualHistory";
    }
    
    return [NSString stringWithFormat:@"%u.jpg", [URLString hash]];
}

- (NSImage*)imageForHistoryItem:(WebHistoryItem*)historyItem
{
    // Decide file path
    NSString*   filePath;
    filePath = [self _filePathForFileName:[self _fileNameForWebHistoryItem:historyItem]];
    
    // Create image
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        NSImage*    image;
        image = [[NSImage alloc] initByReferencingFile:filePath];
        [image autorelease];
        
        return image;
    }
    
    // Check this item is loading or not
    NSEnumerator*   enumerator;
    WebView*        webView;
    enumerator = [_loadingWebViews objectEnumerator];
    while (webView = [enumerator nextObject]) {
        if ([[[webView backForwardList] currentItem] isEqual:historyItem]) {
            return [NSImage imageNamed:@"NowLoading.tiff"];
        }
    }
    
    return [NSImage imageNamed:@"NoImage.tiff"];
}

//--------------------------------------------------------------//
#pragma mark --  WebView notification --
//--------------------------------------------------------------//

- (NSSize)_shrinkedSizeOfSize:(NSSize)size
{
    static float    _ratio = 0.0f;
    if (_ratio == 0.0f) {
        _ratio = SRVisualHistoryMaxImageSizeWidth / SRVisualHistoryMaxImageSizeHeight;
    }
    
    // Shrink size
    float   ratio;
    ratio = size.width / size.height;
    if (ratio > _ratio) {
        if (size.width > SRVisualHistoryMaxImageSizeWidth) {
            size.height = size.height * (SRVisualHistoryMaxImageSizeWidth / size.width);
            size.width = SRVisualHistoryMaxImageSizeWidth;
        }
    }
    else {
        if (size.height > SRVisualHistoryMaxImageSizeHeight) {
            size.width = size.width * (SRVisualHistoryMaxImageSizeHeight / size.height);
            size.height = SRVisualHistoryMaxImageSizeHeight;
        }
    }
    
    return size;
}

- (NSImage*)_imageOfWebView:(WebView*)webView withSize:(NSSize)size
{
    // Draw image
    NSBitmapImageRep*   imageRep;
    [webView lockFocus];
    imageRep = [[NSBitmapImageRep alloc] initWithFocusedViewRect:[webView frame]];
    [webView unlockFocus];
    
    // Create image
    NSImage*    image;
    image = [[NSImage alloc] initWithSize:size];
    [image autorelease];
    [image lockFocus];
    [imageRep drawInRect:NSMakeRect(0, 0, size.width, size.height)];
    [image unlockFocus];
    
    return image;
}

- (void)_saveImage:(NSImage*)image atFile:(NSString*)fileName
{
    // Create bitmap data
    NSDictionary*   properties;
    NSData*         data;
    properties = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:0.9] 
            forKey:NSImageCompressionFactor];
    data = [[NSBitmapImageRep imageRepWithData:[image TIFFRepresentation]] 
            representationUsingType:NSJPEGFileType properties:properties];
    
    // Save data
    [data writeToFile:[self _filePathForFileName:fileName] atomically:YES];
}

- (void)webViewProgressStarted:(NSNotification*)notification
{
    // Get notification web view
    WebView*    webView;
    webView = [notification object];
    
    // Check web view's delegate
    id  delegate;
    delegate = [webView frameLoadDelegate];
    if (!delegate || ![delegate isKindOfClass:[SRMainWindowController class]]) {
        return;
    }
    
    // Register loading web view
    [_loadingWebViews addObject:webView];
    
    // Notify progress
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRVisulaHistoryProgressStartedNotification object:webView];
}

- (void)webViewProgressEstimateChanged:(NSNotification*)notification
{
    // Get notification web view
    WebView*    webView;
    webView = [notification object];
    
    // Check web view's delegate
    id  delegate;
    delegate = [webView frameLoadDelegate];
    if (!delegate || ![delegate isKindOfClass:[SRMainWindowController class]]) {
        return;
    }
    
    // Notify progress
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRVisulaHistoryProgressEstimateChangedNotification object:webView];
}

- (void)webViewProgressFinished:(NSNotification*)notification
{
    // Get notification web view
    WebView*    webView;
    webView = [notification object];
    
    // Check web view's delegate
    id  delegate;
    delegate = [webView frameLoadDelegate];
    if (!delegate || ![delegate isKindOfClass:[SRMainWindowController class]]) {
        return;
    }
    
    // Unregister web view
    [_loadingWebViews removeObject:webView];
    
    // Check superview
    BOOL        hasSuperview;
    NSWindow*   window = nil;
    hasSuperview = [webView superview] != nil;
    if (!hasSuperview) {
        // Insert web view to tmp window
        window = [[NSWindow alloc] initWithContentRect:[webView frame] 
                styleMask:0 
                backing:NSBackingStoreBuffered 
                defer:NO];
        [[window contentView] addSubview:webView];
    }
    
    // Display web view
    [webView display];
    
    // Decide size
    NSSize  shrinkedSize;
    shrinkedSize = [self _shrinkedSizeOfSize:[webView frame].size];
    
    // Create image
    NSImage*    image;
    image = [self _imageOfWebView:webView withSize:shrinkedSize];
    
    // Save image
    [self _saveImage:image atFile:[self _fileNameForWebView:webView]];
    
    // Remove from superview
    if (!hasSuperview) {
        [webView removeFromSuperview];
        [window release];
    }
    
    // Notify progress
    [[NSNotificationCenter defaultCenter] 
            postNotificationName:SRVisulaHistoryProgressFinishedNotification object:webView];
}

@end
