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

#import "SRDownloadShelfStatusCell.h"

static const int    _statusMarginX = 2;

@implementation SRDownloadShelfStatusCell

//--------------------------------------------------------------//
#pragma mark -- Progress indicator --
//--------------------------------------------------------------//

- (NSProgressIndicator*)_progressIndicatorWithDownloadItem:(SRDownloadItem*)downloadItem 
        cellFrame:(NSRect)cellFrame inView:(NSView*)controlView
{
    // Decide progress indicator frame
    NSRect  frame;
    frame.origin.x = cellFrame.origin.x;
    frame.origin.y = cellFrame.origin.y + 4;
    frame.size.width = cellFrame.size.width;
    frame.size.height = 14;
    
    // Get progress indicator
    NSProgressIndicator*    progressIndicator;
    progressIndicator = [downloadItem progressIndicator];
    if (!progressIndicator) {
        // Create progress indicator
        progressIndicator = [[NSProgressIndicator alloc] initWithFrame:frame];
        [progressIndicator setMinValue:0.0];
        [progressIndicator setMaxValue:1.0];
        
        [downloadItem setProgressIndicator:progressIndicator];
        [controlView addSubview:progressIndicator];
        [progressIndicator release];
    }
    
    // Set frame
    if (!NSEqualRects(frame, [progressIndicator frame])) {
        [progressIndicator setFrame:frame];
    }
    
    return progressIndicator;
}

//--------------------------------------------------------------//
#pragma mark -- Drawing --
//--------------------------------------------------------------//

- (void)drawInteriorWithFrame:(NSRect)cellFrame 
        inView:(NSView*)controlView
{
    NSRect  rect;
    
    // Get download item
    SRDownloadItem* item;
    item = [self objectValue];
    
    // Get status
    int status;
    status = [[item valueForKey:@"status"] intValue];
    
    // Calculate percentage
    long long   contentLength;
    long long   downloadedLength;
    double      percentage = 0.0;
    contentLength = [[item valueForKey:@"contentLength"] longLongValue];
    downloadedLength = [[item valueForKey:@"downloadedLength"] longLongValue];
    if (contentLength > 0 && contentLength > 0) {
        percentage = (double)downloadedLength / contentLength;
    }
    
    // Create attributes
    static NSDictionary*    _smallSystemFont = nil;
    static NSDictionary*    _graySmallSystemFont = nil;
    static NSDictionary*    _selectedSmallSystemFont = nil;
    if (!_smallSystemFont) {
        NSMutableParagraphStyle*    paragraph;
        paragraph = [[NSMutableParagraphStyle alloc] init];
        [paragraph setAlignment:NSLeftTextAlignment];
        [paragraph setLineBreakMode:NSLineBreakByTruncatingTail];
        
        _smallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor blackColor], NSForegroundColorAttributeName, 
                paragraph, NSParagraphStyleAttributeName, 
                nil] retain];
        _graySmallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor colorWithCalibratedWhite:0.5f alpha:1.0f], NSForegroundColorAttributeName, 
                paragraph, NSParagraphStyleAttributeName, 
                nil] retain];
        _selectedSmallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor whiteColor], NSForegroundColorAttributeName, 
                paragraph, NSParagraphStyleAttributeName, 
                nil] retain];
        
        [paragraph release];
    }
    
    // Check whether the cell is active and highlighted
    BOOL	highlighted;
    highlighted = ([self isHighlighted] && 
            [[controlView window] isKeyWindow] && 
            [[controlView window] firstResponder] == controlView); 
    
    //
    // Draw upper area
    //
    
    // For progress indicator
    if (status == SRDownloadStatusStarted) {
        // Get progress indicator
        NSProgressIndicator*    progressIndicator;
        progressIndicator = [self _progressIndicatorWithDownloadItem:item 
                cellFrame:cellFrame inView:controlView];
        
        [progressIndicator setIndeterminate:YES];
        [progressIndicator startAnimation:self];
    }
    else if (status == SRDownloadStatusCommitted) {
        // Get progress indicator
        NSProgressIndicator*    progressIndicator;
        progressIndicator = [self _progressIndicatorWithDownloadItem:item 
                cellFrame:cellFrame inView:controlView];
        
        if (contentLength <= 0) {
            if (![progressIndicator isIndeterminate]) {
                [progressIndicator setIndeterminate:YES];
            }
        }
        else {
            if ([progressIndicator isIndeterminate]) {
                [progressIndicator setIndeterminate:NO];
            }
            [progressIndicator setDoubleValue:percentage];
        }
        
        if ([progressIndicator isHidden]) {
            [progressIndicator setHidden:NO];
        }
    }
    else {
        // Get URL
        NSString*   urlString;
        urlString = [item valueForKey:@"urlString"];
        if (urlString) {
            // Draw URL
            NSAttributedString* urlAttrStr;
            NSDictionary*       urlAttributes;
            
            if (highlighted) {
                urlAttributes = _selectedSmallSystemFont;
            }
            else {
                urlAttributes = _graySmallSystemFont;
            }
            
            urlAttrStr = [[NSAttributedString alloc] 
                    initWithString:urlString attributes:urlAttributes];
            [urlAttrStr autorelease];
            
            rect.size.width = cellFrame.size.width - 2 * _statusMarginX;
            rect.size.height = [urlAttrStr size].height;
            rect.origin.x = cellFrame.origin.x + _statusMarginX;
            rect.origin.y = cellFrame.origin.y + 4;
            [urlAttrStr drawInRect:rect];
        }
    }
    
    //
    // Draw lower area
    //
    
    // Create status string
    NSString*   statusStr = nil;
    switch (status) {
    case SRDownloadStatusStarted:
    case SRDownloadStatusCommitted: {
        if (contentLength <= 0) {
            statusStr = @"Preparing for downloading";
        }
        else {
            // Get start time
            CFAbsoluteTime  startTime;
            startTime = [[item valueForKey:@"startTime"] doubleValue];
            
            // Get current time
            CFAbsoluteTime  currentTime;
            currentTime = CFAbsoluteTimeGetCurrent();
            
            if (startTime == 0.0 || currentTime < startTime) {
                statusStr = [NSString stringWithFormat:@"%@ / %@", 
                        HMDataSizeString(downloadedLength), 
                        HMDataSizeString(contentLength)];
            }
            else {
                // Calc speed and expected time
                long long   speed;
                int         expectedTime = -1;
                speed = (long long)(downloadedLength / (currentTime - startTime));
                if (speed > 0) {
                    expectedTime = (int)((contentLength - downloadedLength) / speed) + 1;
                }
                
                if (expectedTime > 0) {
                    statusStr = [NSString stringWithFormat:@"%@ / %@ (%@ /sec) - %@ remaining", 
                            HMDataSizeString(downloadedLength), 
                            HMDataSizeString(contentLength), 
                            HMDataSizeString(speed), 
                            HMTimeString(expectedTime)];
                }
                else {
                    statusStr = [NSString stringWithFormat:@"%@ / %@ (%@ /sec)", 
                            HMDataSizeString(downloadedLength), 
                            HMDataSizeString(contentLength), 
                            HMDataSizeString(speed)];
                }
            }
        }
        
        break;
    }
    case SRDownloadStatusPaused:
    case SRDownloadStatusError: {
        break;
    }
    case SRDownloadStatusCompleted: {
        if (contentLength > 0) {
            statusStr = HMDataSizeString(contentLength);
        }
        break;
    }
    }
    
    // Draw status
    NSAttributedString* statusAttrStr;
    NSDictionary*       statusAttributes;
    
    if (highlighted) {
        statusAttributes = _selectedSmallSystemFont;
    }
    else {
        statusAttributes = _smallSystemFont;
    }
    
    statusAttrStr = [[NSAttributedString alloc] 
            initWithString:statusStr attributes:statusAttributes];
    [statusAttrStr autorelease];
    
    rect.size.width = cellFrame.size.width - 2 * _statusMarginX;
    rect.size.height = [statusAttrStr size].height;
    rect.origin.x = cellFrame.origin.x + _statusMarginX;
    rect.origin.y = cellFrame.origin.y + 22;
    [statusAttrStr drawInRect:rect];
}

@end
