/*
SRDownloader.m

Author: Makoto Kinoshita

Copyright 2004-2006 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 "SRAppController.h"

#import "SRDownloader.h"
#import "SRDownloadItem.h"

#import "SRPrefDefaultKeys.h"

@implementation SRDownloader

//--------------------------------------------------------------//
#pragma mark -- Accessors --
//--------------------------------------------------------------//

- (NSURLDownload*)download
{
    return _download;
}

- (void)setDownload:(NSURLDownload*)download
{
    _download = download;
}

- (SRDownloadItem*)downloadItem
{
#if 1
    return _downloadItem;
#else
    if (!_download) {
        return nil;
    }
    
    // Get managed object context
    NSManagedObjectContext* context;
    context = [[SRAppController sharedInstance] managedObjectContext];
    
    // Get download item
    NSFetchRequest* request;
    request = [[NSFetchRequest alloc] init];
    [request setEntity:
            [NSEntityDescription entityForName:@"DownloadItem" inManagedObjectContext:context]];
    [request setPredicate:
            [NSPredicate predicateWithFormat:@"urlString == %@", [[[_download request] URL] absoluteString]]];
    
    // Execute request
    NSArray*    downloadItems;
    NSError*    error;
    downloadItems = [context executeFetchRequest:request error:&error];
    if (!downloadItems) {
        // Error
        NSLog(@"Failed to fetch download items, %@", [error localizedDescription]);
        return nil;
    }
    
    if ([downloadItems count] == 0) {
        return nil;
    }
    return [downloadItems objectAtIndex:0];
#endif
}

//--------------------------------------------------------------//
#pragma mark -- NSURLDownload delegate --
//--------------------------------------------------------------//

- (void)downloadDidBegin:(NSURLDownload*)download
{
    // Get managed object context
    NSManagedObjectContext* context;
    context = [[SRAppController sharedInstance] managedObjectContext];
    
    // Create download item
    SRDownloadItem* downloadItem;
    downloadItem = [NSEntityDescription insertNewObjectForEntityForName:@"DownloadItem" 
            inManagedObjectContext:context];
    _downloadItem = downloadItem;
    
    // Set URL string
    NSString*   URLString;
    URLString = [[[download request] URL] absoluteString];
    [downloadItem setValue:URLString forKey:@"urlString"];
    [downloadItem setValue:URLString forKey:@"initialURLString"];
    [downloadItem setValue:[NSNumber numberWithBool:YES] forKey:@"active"];
    [downloadItem setValue:NSLocalizedString(UTF8STR("Connecting…"), nil) forKey:@"fileName"];
    
    // Set download status
    [downloadItem setValue:[NSNumber numberWithInt:SRDownloadStatusStarted] 
            forKey:@"status"];
    
    // Clear notify time
    _lastTimeNotify = 0;
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
}

- (NSURLRequest*)download:(NSURLDownload*)download 
        willSendRequest:(NSURLRequest*)request 
        redirectResponse:(NSURLResponse*)redirectResponse
{
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Set URL string
    NSString*   URLString;
    URLString = [[request URL] absoluteString];
    [downloadItem setValue:URLString forKey:@"urlString"];
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
    
    return request;
}

- (void)download:(NSURLDownload*)download 
        didReceiveResponse:(NSURLResponse*)response
{
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Set content length
    long long   contentLength = -1;
    contentLength = [response expectedContentLength];
    if (contentLength <= 0) {
        NSDictionary*   header;
        NSNumber*       contentLengthNumber;
        header = [(NSHTTPURLResponse*)response allHeaderFields];
        contentLengthNumber = [header objectForKey:@"Content-Length"];
        if (contentLengthNumber) {
            contentLength = [contentLengthNumber longLongValue];
        }
    }
    [downloadItem setValue:[NSNumber numberWithLong:contentLength] 
            forKey:@"contentLength"];
    [downloadItem setValue:[NSNumber numberWithLong:0] 
            forKey:@"downloadedLength"];
    
    // Set download status
    [downloadItem setValue:[NSNumber numberWithInt:SRDownloadStatusCommitted] 
            forKey:@"status"];
    [downloadItem setValue:[NSNumber numberWithFloat:CFAbsoluteTimeGetCurrent()] 
            forKey:@"startTime"];
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
}

- (void)download:(NSURLDownload*)download 
        decideDestinationWithSuggestedFilename:(NSString*)fileName
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    NSFileManager*  fileMgr;
    fileMgr = [NSFileManager defaultManager];
    
    // Get download file path
    NSString*       downloadPath;
    downloadPath = [defaults stringForKey:SRDownloadPath];
    if (!downloadPath) {
        // Default path is desktop
        downloadPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Desktop"];
    }
    
 	// Make date sub directory
	if ([defaults boolForKey:SRDownloadSaveInDateDirectory]) {
        NSString*   dateDirPath;
        BOOL        isDirectory;
        dateDirPath = [downloadPath stringByAppendingPathComponent:
                [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d" timeZone:nil locale:nil]];
        
        if (![fileMgr fileExistsAtPath:dateDirPath isDirectory:&isDirectory] || !isDirectory) {
            // Create directory
            HMCreateDirectoryFile(dateDirPath, YES);
        }
        downloadPath = dateDirPath;
	}
    
    // Create file wrapper path
    NSString*       fileWrapperPath;
    fileWrapperPath = [downloadPath stringByAppendingPathComponent:fileName];
    fileWrapperPath = [fileWrapperPath stringByAppendingPathExtension:@"download"];
    fileWrapperPath = [fileMgr makeUniqueFilePath:fileWrapperPath];
    if (![fileMgr createDirectoryAtPath:fileWrapperPath attributes:nil]) {
        // Error
        NSLog(@"Failed to create directory at %@", fileWrapperPath);
        return;
    }
    
    // Create file wrapper
    NSFileWrapper*  fileWrapper;
    fileWrapper = [[NSFileWrapper alloc] initWithPath:fileWrapperPath];
    if (![fileWrapper writeToFile:fileWrapperPath atomically:YES updateFilenames:NO]) {
        // Error
        NSLog(@"Failed to create file wrapper at %@", fileWrapperPath);
        return;
    }
    
    // Set destination file path
    [download setDestination:[fileWrapperPath stringByAppendingPathComponent:fileName] 
            allowOverwrite:NO];
}

- (void)download:(NSURLDownload*)download 
        didCreateDestination:(NSString*)path
{
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Set download file path
    [downloadItem setValue:path forKey:@"filePath"];
    [downloadItem setValue:[path lastPathComponent] forKey:@"fileName"];
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
}

- (void)download:(NSURLDownload*)download 
        didReceiveDataOfLength:(unsigned)length
{
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Increase data length
    long    downloadedLength;
    downloadedLength = [[downloadItem valueForKey:@"downloadedLength"] longValue];
    [downloadItem setValue:[NSNumber numberWithLong:downloadedLength + length] forKey:@"downloadedLength"];
    
    // Get current time
    CFAbsoluteTime  time;
    time = CFAbsoluteTimeGetCurrent();
    if (_lastTimeNotify == 0 || time - _lastTimeNotify > 0.5f) {
        _lastTimeNotify = time;
        
        // Notify status change
        [downloadItem willChangeValueForKey:@"itself"];
        [downloadItem didChangeValueForKey:@"itself"];
    }
}

- (void)downloadDidFinish:(NSURLDownload*)download
{
    NSUserDefaults* defaults;
    defaults = [NSUserDefaults standardUserDefaults];
    
    NSFileManager*  fileMgr;
    fileMgr = [NSFileManager defaultManager];
    
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Make status comleted
    [downloadItem setValue:[NSNumber numberWithInt:SRDownloadStatusCompleted] forKey:@"status"];
    
    // Set data length
    long    contentLength, downloadedLength;
    contentLength = [[downloadItem valueForKey:@"contentLength"] longValue];
    downloadedLength = [[downloadItem valueForKey:@"downloadedLength"] longValue];
    if (downloadedLength < contentLength) {
        [downloadItem setValue:[NSNumber numberWithLong:contentLength] forKey:@"downloadedLength"]; 
    }
    
    // Get downloaded file from file wrapper
    NSString*   downloadedFilePath;
    NSString*   parentDirectory;
    downloadedFilePath = [downloadItem valueForKey:@"filePath"];
    parentDirectory = [downloadedFilePath stringByDeletingLastPathComponent];
    if ([[parentDirectory pathExtension] isEqualToString:@"download"]) {
        NSString*   newFilePath;
        newFilePath = [[parentDirectory stringByDeletingLastPathComponent] 
                stringByAppendingPathComponent:[downloadedFilePath lastPathComponent]];
        newFilePath = [fileMgr makeUniqueFilePath:newFilePath];
        
        // Move downloaded file
        if (![fileMgr movePath:downloadedFilePath toPath:newFilePath handler:nil]) {
            // Error
            NSLog(@"Failed to move downloaded file");
        }
        else {
            // Change downloaded file path
            [downloadItem setValue:newFilePath forKey:@"filePath"];
            
            // Remove .download file wrapper
            if (![fileMgr removeFileAtPath:parentDirectory handler:nil]) {
                // Error
                NSLog(@"Failed to remove file download wrapper");
            }
        }
    }
    
// For Growl support
#ifdef SR_SUPPORT_GROWL
    // Get file name and URL
    NSString*   fileName;
    NSString*   URLString;
    fileName = [historyItem fileName];
    URLString = [historyItem URLString];
    
    // Create title and description
    NSString*   title;
    NSString*   description;
    title = NSLocalizedString(@"Download is completed", nil);
    description = [NSString stringWithFormat:@"%@\n%@", fileName, URLString];
    
    // Notify Growl
    [GrowlApplicationBridge notifyWithTitle:title 
            description:description 
            notificationName:SRGrowlDownloadCompletedNotification 
            iconData:nil 
            priority:0 
            isSticky:NO 
            clickContext:nil];
#endif // SR_SUPPORT_GROWL
    
    // Remove it from active items
#if 0
    WebPreferences* preferences;
    BOOL            isPrivate;
    preferences = [SRPreferencesController defaultWebPreferences];
    isPrivate = [preferences privateBrowsingEnabled];
    if ([defaults integerForKey:SRDownloadItemRemove] == SRDownloadItemRemoveAutomatically || isPrivate) {
        [self removeDownloadForItem:historyItem];
    }
    else {
        // For notification
        if (![_statusChangedItems containsObject:historyItem]) {
            [_statusChangedItems addObject:historyItem];
        }
    }
#endif
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
}

- (void)download:(NSURLDownload*)download 
        didFailWithError:(NSError*)error
{
    // Get download item
    SRDownloadItem* downloadItem;
    downloadItem = [self downloadItem];
    
    // Notify status change
    [downloadItem willChangeValueForKey:@"itself"];
    [downloadItem didChangeValueForKey:@"itself"];
}

@end
