/*
SRDownloadHistoryItem.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 "SRDownloadHistoryItem.h"

#import "SRUtil.h"

static NSString*    SRDownloadHistoryItemDownload = @"Download";
static NSString*    SRDownloadHistoryItemURLString = @"URLString";
static NSString*    SRDownloadHistoryItemFileName = @"FileName";
static NSString*    SRDownloadHistoryItemRelatedURLString = @"RelatedURLString";
static NSString*    SRDownloadHistoryItemFilePath = @"FilePath";
static NSString*    SRDownloadHistoryItemIcon = @"Icon";
static NSString*    SRDownloadHistoryItemDownloadedLength = @"DownloadedLength";
static NSString*    SRDownloadHistoryItemExpectedLength = @"ExpectedLength";
static NSString*    SRDownloadHistoryItemStartTime = @"StartTime";
static NSString*    SRDownloadHistoryItemResumeInfo = @"ResumeInfo";
static NSString*    SRDownloadHistoryItemStatus = @"Status";
static NSString*    SRDownloadHistoryItemUUID = @"UUID";

@implementation SRDownloadHistoryItem

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

- (void)_setUUID
{
    // Set UUID info dictionary
    [_infoDict setObject:SRCreateUUID() forKey:SRDownloadHistoryItemUUID];
}

- (id)init
{
    self = [super init];
    if (!self) {
        return self;
    }
    
    // Initialize member variables
    _infoDict = [[NSMutableDictionary dictionary] retain];
    [self _setUUID];
    
    return self;
}

- (id)initWithHistoryDictionary:(NSDictionary*)dict
{
    self = [super init];
    if (!self) {
        return self;
    }
    
    // Copy from dictionary
    _infoDict = [[NSMutableDictionary dictionaryWithDictionary:dict] retain];
    
    // Set icon
    NSString*   fileName;
    NSImage*    icon;
    fileName = [_infoDict objectForKey:SRDownloadHistoryItemFileName];
    icon = [[NSWorkspace sharedWorkspace] iconForFileType:[fileName pathExtension]];
    if (icon) {
        [icon setSize:NSMakeSize(16, 16)];
        [_infoDict setObject:icon forKey:SRDownloadHistoryItemIcon];
    }
    
    [self _setUUID];
    
    return self;
}

- (id)copyWithZone:(NSZone*)zone
{
    SRDownloadHistoryItem*  item;
    item = [[SRDownloadHistoryItem alloc] init];
    [item->_infoDict release];
    item->_infoDict = [_infoDict retain];
    
    return item;
}

- (unsigned)hash
{
    return [[_infoDict objectForKey:SRDownloadHistoryItemUUID] hash];
}

- (BOOL)isEqual:(id)object
{
    id  selfUUID, objectUUID;
    selfUUID = [_infoDict objectForKey:SRDownloadHistoryItemUUID];
    objectUUID = [((SRDownloadHistoryItem*)object)->_infoDict objectForKey:SRDownloadHistoryItemUUID];
    return [selfUUID isEqual:objectUUID];
}

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

//--------------------------------------------------------------//
#pragma mark -- Download information --
//--------------------------------------------------------------//

- (void)setDownload:(NSURLDownload*)download
{
    if (!download) {
        return;
    }
    
    [_infoDict setObject:download forKey:SRDownloadHistoryItemDownload];
}

- (NSURLDownload*)download
{
    return [_infoDict objectForKey:SRDownloadHistoryItemDownload];
}

- (void)setRequest:(NSURLRequest*)request
{
    // Get URL
    NSURL*  url;
    url = [request URL];
    if (!url) {
        return;
    }
    
    // Set URLString
    NSString*   URLString;
    URLString = [url absoluteString];
    if (URLString) {
        [_infoDict setObject:URLString forKey:SRDownloadHistoryItemURLString];
    }
    
    // Set file name
    NSString*   fileName;
    fileName = [[url path] lastPathComponent];
    if (fileName) {
        [_infoDict setObject:fileName forKey:SRDownloadHistoryItemFileName];
    }
    
    // Set releated URL string
    NSString*   relatedURLString;
    relatedURLString = [request valueForHTTPHeaderField:@"Referer"];
    if (relatedURLString) {
        [_infoDict setObject:relatedURLString forKey:SRDownloadHistoryItemRelatedURLString];
    }
    
    // Set icon
    NSImage*    icon;
    icon = [[NSWorkspace sharedWorkspace] iconForFileType:[fileName pathExtension]];
    if (icon) {
        [icon setSize:NSMakeSize(16, 16)];
        [_infoDict setObject:icon forKey:SRDownloadHistoryItemIcon];
    }
}

- (void)setResponse:(NSURLResponse*)response
{
    // Set expected length
    long long length;
    length = [response expectedContentLength];
    [_infoDict setObject:[NSNumber numberWithLongLong:length] 
            forKey:SRDownloadHistoryItemExpectedLength];
}

- (NSString*)URLString
{
    return [_infoDict objectForKey:SRDownloadHistoryItemURLString];
}

- (NSString*)fileName
{
    return [_infoDict objectForKey:SRDownloadHistoryItemFileName];
}

- (NSString*)relatedURLString
{
    return [_infoDict objectForKey:SRDownloadHistoryItemRelatedURLString];
}

- (NSImage*)icon
{
    return [_infoDict objectForKey:SRDownloadHistoryItemIcon];
}

- (NSString*)downloadedFilePath
{
    return [_infoDict objectForKey:SRDownloadHistoryItemFilePath];
}

- (void)setDownloadedFilePath:(NSString*)path
{
    if (!path) {
        return;
    }
    
    [_infoDict setObject:path forKey:SRDownloadHistoryItemFilePath];
    
    // Set downloaded file name
    NSString*   fileName;
    fileName = [path lastPathComponent];
    if (fileName) {
        [_infoDict setObject:fileName forKey:SRDownloadHistoryItemFileName];
    }
}

- (NSString*)downloadedFileName
{
    return [_infoDict objectForKey:SRDownloadHistoryItemFileName];
}

- (long long)expectedLength
{
    NSNumber*   length;
    length = [_infoDict objectForKey:SRDownloadHistoryItemExpectedLength];
    if (!length) {
        return -1;
    }
    
    return [length longLongValue];
}

- (long long)downloadedLength
{
    NSNumber*   length;
    length = [_infoDict objectForKey:SRDownloadHistoryItemDownloadedLength];
    if (!length) {
        return -1;
    }
    
    return [length longLongValue];
}

- (void)setDownloadedLength:(long long)length
{
    [_infoDict setObject:[NSNumber numberWithLongLong:length] 
            forKey:SRDownloadHistoryItemDownloadedLength];
}

- (void)increaseDownloadedLength:(long long)length
{
    // Get downloaded length
    long long   downloadedLength;
    downloadedLength = [self downloadedLength];
    if (downloadedLength == -1) {
        downloadedLength = 0;
    }
    
    // Set increased length
    [self setDownloadedLength:downloadedLength + length];
}

- (void)resetLength
{
    [_infoDict setObject:[NSNumber numberWithLongLong:-1] 
            forKey:SRDownloadHistoryItemExpectedLength];
    [self setDownloadedLength:0];
}

- (NSDate*)startTime
{
    return [_infoDict objectForKey:SRDownloadHistoryItemStartTime];
}

- (void)setStartTime:(NSDate*)date
{
    if (!date) {
        return;
    }
    
    [_infoDict setObject:date forKey:SRDownloadHistoryItemStartTime];
}

//--------------------------------------------------------------//
#pragma mark -- Download resume information --
//--------------------------------------------------------------//

- (NSDictionary*)resumeInfo
{
    return [_infoDict objectForKey:SRDownloadHistoryItemResumeInfo];
}

- (void)setResumeInfo:(NSDictionary*)resumeInfo
{
    if (!resumeInfo) {
        [_infoDict removeObjectForKey:SRDownloadHistoryItemResumeInfo];
        return;
    }
    
    [_infoDict setObject:resumeInfo forKey:SRDownloadHistoryItemResumeInfo];
}

//--------------------------------------------------------------//
#pragma mark -- Status --
//--------------------------------------------------------------//

- (SRDownloadItemStatus)status
{
    NSNumber*   number;
    number = [_infoDict objectForKey:SRDownloadHistoryItemStatus];
    if (!number) {
        return SRDownloadStatusUnknown;
    }
    
    return [number intValue];
}

- (void)setStatus:(SRDownloadItemStatus)status
{
    [_infoDict setObject:[NSNumber numberWithInt:status] forKey:SRDownloadHistoryItemStatus];
}

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

- (NSDictionary*)historyDictionary
{
    static NSArray* _copiedKey = nil;
    if (!_copiedKey) {
        _copiedKey = [[NSArray arrayWithObjects:
                SRDownloadHistoryItemURLString, SRDownloadHistoryItemFileName, 
                SRDownloadHistoryItemRelatedURLString, SRDownloadHistoryItemFilePath, 
                SRDownloadHistoryItemDownloadedLength, SRDownloadHistoryItemExpectedLength, 
                SRDownloadHistoryItemResumeInfo, nil] retain];
    }
    
    NSMutableDictionary*    historyDict;
    historyDict = [NSMutableDictionary dictionary];
    
    // Check object value for key
    NSEnumerator*   enumerator;
    NSString*       key;
    enumerator = [_copiedKey objectEnumerator];
    while (key = [enumerator nextObject]) {
        id  object;
        object = [_infoDict objectForKey:key];
        if (object) {
            [historyDict setObject:object forKey:key];
        }
    }
    
    return historyDict;
}

@end
