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

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

@implementation SRDownloadStatusCell

- (id)init
{
    self = [super init];
    if (self) {
    }
    
    return self;
}

- (id)copyWithZone:(NSZone*)zone
{
    SRDownloadStatusCell*   cell;
    cell = [[SRDownloadStatusCell alloc] init];
    [cell setObjectValue:[self objectValue]];
    cell->_progressIndicator = _progressIndicator;
    
    return cell;
}

- (NSProgressIndicator*)progressIndicator
{
    return _progressIndicator;
}

- (void)setProgressIndicator:(NSProgressIndicator*)progressIndicator
{
    // Do not retain it
    _progressIndicator = progressIndicator;
}

- (void)drawInteriorWithFrame:(NSRect)cellFrame 
        inView:(NSView*)controlView
{
    NSRect  rect;
    
    // Get download history item
    SRDownloadHistoryItem*  item;
    item = [self objectValue];
    
    // Create attributes
    static NSDictionary*    _smallSystemFont = nil;
    static NSDictionary*    _graySmallSystemFont = nil;
    static NSDictionary*    _selectedSmallSystemFont = nil;
    if (!_smallSystemFont) {
        _smallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], 
                NSFontAttributeName, 
                nil] retain];
        _graySmallSystemFont = [[NSDictionary dictionaryWithObjectsAndKeys:
                [NSFont systemFontOfSize:[NSFont smallSystemFontSize]], NSFontAttributeName, 
                [NSColor darkGrayColor], 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   expectedLength;
    long long   downloadedLength;
    double      percentage = 0.0;
    expectedLength = [item expectedLength];
    downloadedLength = [item downloadedLength];
    if (expectedLength > 0 && expectedLength > 0) {
        percentage = (double)downloadedLength / expectedLength;
    }
    
    // Draw icon
    NSImage*    icon;
    NSSize      iconSize;
    NSPoint     iconPoint;
    icon = [item icon];
    iconSize = [icon size];
    if ([icon isFlipped]) {
        iconPoint.x = cellFrame.origin.x;
        iconPoint.y = cellFrame.origin.y + 1;
    }
    else {
        iconPoint.x = cellFrame.origin.x;
        iconPoint.y = cellFrame.origin.y + iconSize.height + 1;
    }
    [icon dissolveToPoint:iconPoint fraction:1.0];
    
    // Draw file name
    NSString*           downloadedFileName;
    NSAttributedString* fileName;
    NSDictionary*       strAttributes;
    
    if (highlighted) {
        strAttributes = _selectedSmallSystemFont;
    }
    else {
        strAttributes = _smallSystemFont;
    }
    
    downloadedFileName = [item downloadedFileName];
    if (!downloadedFileName) {
        downloadedFileName = @" "; // dummy
    }
    fileName = [[NSAttributedString alloc] 
            initWithString:downloadedFileName 
            attributes:strAttributes];
    [fileName autorelease];
    
    rect.origin.x = cellFrame.origin.x + iconSize.width + _statusMarginX;
    rect.origin.y = cellFrame.origin.y + _statusMarginY;
    rect.size.width = cellFrame.size.width - iconSize.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 status]) {
    // For active
    case SRDownloadStatusActive: {
        // Set progress indicator
        rect.origin.y += rect.size.height + 2;
        rect.size.width -= 40;
        rect.size.height = [_progressIndicator frame].size.height;
        [_progressIndicator setFrame:rect];
        [_progressIndicator sizeToFit];
        
        if (expectedLength == -1 || expectedLength == 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];
        [percentageStr autorelease];
        
        NSSize  percentageSize;
        percentageSize = [percentageStr size];
        rect.origin.x = rect.origin.x + rect.size.width + 4 + _hundredPercentW - percentageSize.width;
        rect.origin.y -= 2;
        rect.size.width = percentageSize.width;
        rect.size.height = percentageSize.height;
        [percentageStr drawInRect:rect];
        
        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
