/*
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;
    frame.size.height = 11;
    
    // Get progress indicator
    HMBlkProgressIndicator* blkProgressIndicator;
    blkProgressIndicator = [downloadItem blkProgressIndicator];
    if (!blkProgressIndicator) {
        // Create progress indicator
        blkProgressIndicator = [[HMBlkProgressIndicator alloc] initWithFrame:frame];
        [blkProgressIndicator setMinValue:0.0];
        [blkProgressIndicator setMaxValue:1.0];
        
        [downloadItem setBlkProgressIndicator:blkProgressIndicator];
        [controlView addSubview:blkProgressIndicator];
        [blkProgressIndicator release];
    }
    
    // Set frame
    if (!NSEqualRects(frame, [blkProgressIndicator frame])) {
        [blkProgressIndicator setFrame:frame];
    }
    
    return blkProgressIndicator;
}

//--------------------------------------------------------------//
#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];
    }
    
    // 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: {
        // Get progress indicator
        HMBlkProgressIndicator* progressIndicator;
        progressIndicator = [self _progressIndicatorWithDownloadItem:item 
                cellFrame:cellFrame inView:controlView];
        
        [progressIndicator setIndeterminate:YES];
        [progressIndicator startAnimation:self];
        
        break;
    }
    // For commited status
    case SRDownloadStatusCommitted: {
        // Get progress indicator
        HMBlkProgressIndicator* 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];
        }
        
#if 0
        // 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];
#endif
        
        // Draw status
        NSString*           statusStr;
        NSAttributedString* statusAttrStr;
        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 || startTime == currentTime) {
                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)];
                }
            }
        }
        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: {
        // 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: {
        // 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
