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

static const int    _statusMarginX = 2;
static const int    _statusMarginY = 6;

@implementation SRDownloadStatusCell

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

- (HMBlkProgressIndicator*)_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 + 24;
    frame.size.width = cellFrame.size.width - 40;
    frame.size.height = 11;
    
    // Get progress indicator
    HMBlkProgressIndicator* progressIndicator;
    progressIndicator = [downloadItem progressIndicator];
    if (!progressIndicator) {
        // Create progress indicator
        progressIndicator = [[HMBlkProgressIndicator 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];
    
    // Create attributes
    static NSDictionary*    _smallSystemFont = nil;
    static NSDictionary*    _miniSystemFont = nil;
    static NSDictionary*    _graySmallSystemFont = nil;
    static NSDictionary*    _selectedSmallSystemFont = nil;
    if (!_smallSystemFont) {
        _smallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor whiteColor], NSForegroundColorAttributeName, 
                nil] retain];
        _miniSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:9.0f], NSFontAttributeName, 
                [NSColor whiteColor], NSForegroundColorAttributeName, 
                nil] retain];
        _graySmallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor colorWithCalibratedWhite:0.8f alpha:1.0f], NSForegroundColorAttributeName, 
                nil] retain];
        _selectedSmallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor whiteColor], NSForegroundColorAttributeName, 
                nil] retain];
    }
    
    // Get progress indicator
    HMBlkProgressIndicator* progressIndicator;
    progressIndicator = [self _progressIndicatorWithDownloadItem:item 
            cellFrame:cellFrame inView:controlView];
    
    // Check whether the cell is active and highlighted
    BOOL	highlighted;
    highlighted = ([self isHighlighted] && 
            [[controlView window] isKeyWindow] && 
            [[controlView window] firstResponder] == controlView); 
    
    // 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;
    }
    
    // Draw file name
    NSString*           downloadedFileName;
    NSAttributedString* fileName;
    NSDictionary*       strAttributes;
    
    if (highlighted) {
        strAttributes = _selectedSmallSystemFont;
    }
    else {
        strAttributes = _smallSystemFont;
    }
    
    downloadedFileName = [item valueForKey:@"fileName"];
    if (!downloadedFileName) {
        downloadedFileName = @" "; // dummy
    }
    fileName = [[NSAttributedString alloc] 
            initWithString:downloadedFileName 
            attributes:strAttributes];
    [fileName autorelease];
    
    rect.origin.x = cellFrame.origin.x + _statusMarginX;
    rect.origin.y = cellFrame.origin.y + _statusMarginY;
    rect.size.width = cellFrame.size.width - 2 * _statusMarginX;
    rect.size.height = [fileName size].height;
    [fileName drawInRect:rect];
    
    // Decide string color
    if (highlighted) {
        strAttributes = _selectedSmallSystemFont;
    }
    else {
        strAttributes = _graySmallSystemFont;
    }
    
    // Switch by status
    switch ([[item valueForKey:@"status"] intValue]) {
    // For started status
    case SRDownloadStatusStarted: {
        [progressIndicator setIndeterminate:YES];
        [progressIndicator startAnimation:self];
        
        break;
    }
    // For commited status
    case SRDownloadStatusCommitted: {
        if (contentLength == -1 || contentLength == 0) {
            if (![progressIndicator isIndeterminate]) {
                [progressIndicator setIndeterminate:YES];
            }
        }
        else {
            if ([progressIndicator isIndeterminate]) {
                [progressIndicator setIndeterminate:NO];
            }
            [progressIndicator setDoubleValue:percentage];
        }
        
        if ([progressIndicator isHidden]) {
            [progressIndicator setHidden:NO];
        }
        
        // Draw percentage
        static int  _hundredPercentW = -1;
        if (_hundredPercentW == -1) {
            NSAttributedString* hundredPercent;
            hundredPercent = [[NSAttributedString alloc] 
                    initWithString:@"100%" 
                    attributes:_smallSystemFont];
            [hundredPercent autorelease];
            _hundredPercentW = [hundredPercent size].width;
        }
        NSAttributedString* percentageStr;
        percentageStr = [[NSAttributedString alloc] 
                initWithString:[NSString stringWithFormat:@"%d%%", (int)(percentage * 100)] 
                attributes:highlighted ? _selectedSmallSystemFont : _smallSystemFont];
        
        NSSize  percentageSize;
        percentageSize = [percentageStr size];
        rect.origin.x = cellFrame.origin.x + cellFrame.size.width - percentageSize.width;
        rect.origin.y = cellFrame.origin.y + 18;
        rect.size = percentageSize;
        [percentageStr drawInRect:rect];
        [percentageStr release];
        
        // Draw status
        NSString*           statusStr;
        NSAttributedString* statusAttrStr;
        if (contentLength == -1 || 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 || startTime == currentTime) {
                statusStr = [NSString stringWithFormat:@"%@ / %@", 
                        SRCreateDataSizeString(downloadedLength), 
                        SRCreateDataSizeString(contentLength)];
            }
            else {
                // Calc speed and expected time
                long long   speed;
                int         expectedTime;
                speed = (long long)(downloadedLength / (currentTime - startTime));
                expectedTime = (int)((contentLength - downloadedLength) / speed) + 1;
                
                statusStr = [NSString stringWithFormat:@"%@ / %@ (%@ /sec) - %d sec", 
                        SRCreateDataSizeString(downloadedLength), 
                        SRCreateDataSizeString(contentLength), 
                        SRCreateDataSizeString(speed), 
                        expectedTime];
            }
        }
        statusAttrStr = [[NSAttributedString alloc] 
                initWithString:statusStr 
                attributes:highlighted ? _miniSystemFont : _miniSystemFont];
        
        NSSize  statusSize;
        statusSize = [statusAttrStr size];
        rect.origin.x = cellFrame.origin.x + _statusMarginX;
        rect.origin.y = cellFrame.origin.y + cellFrame.size.height - 4 - statusSize.height;
        rect.size = statusSize;
        [statusAttrStr drawInRect:rect];
        [statusAttrStr release];
        
        break;
    }
    // For paused
    case SRDownloadStatusPaused: {
        // Hide progress indicator
        if (![progressIndicator isHidden]) {
            [progressIndicator setHidden:YES];
        }
        
        // Draw paused
        NSString*           paused;
        NSAttributedString* statusStr;
        paused = [NSString stringWithFormat:NSLocalizedString(@"Paused (%d%% done)", nil), 
                (int)(percentage * 100)];
        statusStr = [[NSAttributedString alloc] 
                initWithString:paused attributes:strAttributes];
        [statusStr autorelease];
        
        rect.origin.y += rect.size.height + 2;
        [statusStr drawAtPoint:rect.origin];
        
        break;
    }
    // For completed
    case SRDownloadStatusCompleted: {
        // Hide progress indicator
        if (![progressIndicator isHidden]) {
            [progressIndicator setHidden:YES];
        }
        
        // Draw completed
        NSString*           completed;
        NSAttributedString* statusStr;
        completed = [NSString stringWithFormat:NSLocalizedString(@"Completed", nil)];
        statusStr = [[NSAttributedString alloc] 
                initWithString:completed attributes:strAttributes];
        [statusStr autorelease];
        
        rect.origin.y += rect.size.height + 2;
        [statusStr drawAtPoint:rect.origin];
        
        break;
    }
    // For unknown
    case SRDownloadStatusUnknown: {
        break;
    }
    }
}

@end
