/*
SRDownloadShelf.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 "SRDownloader.h"
#import "SRDownloadItem.h"

#import "SRDownloadShelf.h"
#import "SRDownloadShelfTitleCell.h"
#import "SRDownloadShelfStatusCell.h"

#import "SRDownloadContextMenu.h"

@interface SRDownloadShelf (private)

// Display style
- (void)_updateLowerView;
@end

@implementation SRDownloadShelf

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

- (id)initWithBundle:(NSBundle*)bundle
{
    self = [super initWithBundle:bundle];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables

    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(downloadDidBegin:) 
            name:@"SRDownloadDidBeginNotification" object:nil];
    [center addObserver:self selector:@selector(downloadDidReceiveResponse:) 
            name:@"SRDownloadDidReceiveResponseNotification" object:nil];
    [center addObserver:self selector:@selector(downloadDidFinish:) 
            name:@"SRDownloadDidFinishNotification" object:nil];
    [center addObserver:self selector:@selector(downloadDidFail:) 
            name:@"SRDownloadDidFailNotification" object:nil];
    [center addObserver:self selector:@selector(downloadStatusChanged:) 
            name:@"SRDownloadStatusChangedNotification" object:nil];
    
    return self;
}

- (void)didLoad
{
    // Create buttons
    _contextButton = [[NSClassFromString(@"HMMenuButton") alloc] initWithFrame:NSMakeRect(0, 0, 31, 19)];
    [_contextButton setButtonType:NSMomentaryChangeButton];
    [_contextButton setBezelStyle:NSRegularSquareBezelStyle];
    [_contextButton setBordered:NO];
    [_contextButton setImage:[NSImage imageNamed:@"shelfContext"]];
    [_contextButton setSelectedImage:[NSImage imageNamed:@"shelfPressedBackgroundL"]];
    [_contextButton setFont:[NSFont systemFontOfSize:[NSFont systemFontSize]]];
    [_contextButton setDelegate:self];
    [_contextButton setTarget:self];
    
    // Configure split view
    [_splitView setSplitType:HMSplitWide];
    
    // Set download title cell
    NSTableColumn*              column;
    NSCell*                     oldCell;
    SRDownloadShelfTitleCell*   titleCell;
    column = [_tableView tableColumnWithIdentifier:@"title"];
    oldCell = [column dataCell];
    titleCell = [[SRDownloadShelfTitleCell alloc] init];
    [titleCell setFont:[oldCell font]];
    [column setDataCell:titleCell];
    [titleCell release];
    
    // Set download status cell
    SRDownloadShelfStatusCell*  statusCell;
    column = [_tableView tableColumnWithIdentifier:@"status"];
    oldCell = [column dataCell];
    statusCell = [[SRDownloadShelfStatusCell alloc] init];
    [statusCell setFont:[oldCell font]];
    [column setDataCell:statusCell];
    [statusCell release];
    
    // Reload data
    [_tableView reloadData];
    
    // Update appearance
    [self _updateLowerView];
}

- (void)dealloc
{
    [_contextButton release], _contextButton = nil;
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Download items --
//--------------------------------------------------------------//

- (NSArray*)selectedDownloadItems
{
    // Get selected rows
    NSIndexSet* indexSet;
    indexSet = [_tableView selectedRowIndexes];
    
    // Collect download items
    NSArray*        downloadItems;
    NSMutableArray* selectedItems;
    unsigned int    index;
    downloadItems = [[NSClassFromString(@"SRDownloadManager") sharedInstance] items];
    selectedItems = [NSMutableArray array];
    index = [indexSet firstIndex];
    do {
        if ([downloadItems count] > index) {
            [selectedItems addObject:[downloadItems objectAtIndex:index]];
        }
    } while ((index = [indexSet indexGreaterThanIndex:index]) != NSNotFound);
    
    return selectedItems;
}

//--------------------------------------------------------------//
#pragma mark -- Bar buttons --
//--------------------------------------------------------------//

- (NSArray*)rightBarButtons
{
    return [NSArray arrayWithObjects:_contextButton, nil];
}

//--------------------------------------------------------------//
#pragma mark -- Display style --
//--------------------------------------------------------------//

- (void)_updateLowerView
{
    // Get content size
    NSSize  contentSize;
    contentSize = [_scrollView contentSize];
    
    // Get selected download items
    NSArray*    downloadItems;
    downloadItems = [self selectedDownloadItems];
    if ([downloadItems count] == 0) {
        // Clear document view
        [_scrollView setDocumentView:nil];
        return;
    }
    
    // Get old view
    NSView* oldView;
    oldView = [_scrollView documentView];
    
    // For multiple view
    if ([downloadItems count] > 1) {
        return;
    }
    
    // Swap view
    NSView* newView;
    newView = _itemView;
    if (oldView != newView) {
        NSRect  frame;
        frame = [newView frame];
        frame.origin.x = 0;
        frame.origin.y = 0;
        frame.size.width = contentSize.width;
        [newView setFrame:frame];
        
        [_scrollView setDocumentView:newView];
    }
    
    // Get download item
    id  downloadItem;
    downloadItem = [downloadItems objectAtIndex:0];
    
    // Get bundle
    NSBundle*   bundle;
    bundle = [NSBundle bundleForClass:[self class]];
    
    // Get stauts
    int status;
    status = [[downloadItem valueForKey:@"status"] intValue];
    
    // Calculate percentage
    long long   contentLength;
    long long   downloadedLength;
    double      percentage = 0.0;
    contentLength = [[downloadItem valueForKey:@"contentLength"] longLongValue];
    downloadedLength = [[downloadItem valueForKey:@"downloadedLength"] longLongValue];
    if (contentLength > 0 && contentLength > 0) {
        percentage = (double)downloadedLength / contentLength;
    }
    
    // Set values
    [_itemContent setValue:[downloadItem icon] forKey:@"icon"];
    [_itemContent setValue:[downloadItem valueForKey:@"fileName"] forKey:@"title"];
    [_itemContent setValue:[downloadItem valueForKey:@"filePath"] forKey:@"savedPath"];
    
    NSString*   statusStr = @"";
    switch (status) {
    case SRDownloadStatusStarted: {
        statusStr = [bundle localizedStringForKey:@"Preparing for downloading" value:nil table:nil];
        break;
    }
    case SRDownloadStatusCommitted: {
        statusStr = [bundle localizedStringForKey:@"Downloading" value:nil table:nil];
        break;
    }
    case SRDownloadStatusPaused: {
        statusStr = [bundle localizedStringForKey:@"Canceled" value:nil table:nil];
        break;
    }
    case SRDownloadStatusCompleted: {
        statusStr = [bundle localizedStringForKey:@"Done" value:nil table:nil];
        break;
    }
    case SRDownloadStatusError: {
        statusStr = [bundle localizedStringForKey:@"Error happend" value:nil table:nil];
        break;
    }
    }
    [_itemContent setValue:statusStr forKey:@"status"];
    
    NSString*   fileSize = [bundle localizedStringForKey:@"(Unknown)" value:nil table:nil];
    switch (status) {
    case SRDownloadStatusStarted:
    case SRDownloadStatusCompleted: {
        if (contentLength > 0) {
            fileSize = HMDataSizeString(contentLength);
        }
        break;
    }
    case SRDownloadStatusCommitted:
    case SRDownloadStatusPaused:
    case SRDownloadStatusError: {
        if (contentLength > 0 && downloadedLength > 0) {
            fileSize = [NSString stringWithFormat:@"%@ / %@ (%d%%)", 
                    HMDataSizeString(contentLength), 
                    HMDataSizeString(downloadedLength), 
                    (int)percentage];
        }
        break;
    }
    }
    [_itemContent setValue:fileSize forKey:@"fileSize"];
    
    NSString*   dateStr;
    dateStr = [[downloadItem valueForKey:@"date"] description];
    [_itemContent setValue:dateStr forKey:@"date"];
    
    [_itemContent setValue:[downloadItem valueForKey:@"urlString"] forKey:@"fileUrl"];
    [_itemContent setValue:[downloadItem valueForKey:@"relatedURLString"] forKey:@"downloadPage"];
}

//--------------------------------------------------------------//
#pragma mark -- Action --
//--------------------------------------------------------------//

- (void)downloadAction:(id)sender
{
}

- (void)downloadAllAction:(id)sender
{
}

- (void)openReferenceURLAction:(id)sender
{
}

- (void)deleteDownloadHistoryAction:(id)sender
{
}

//--------------------------------------------------------------//
#pragma mark -- SRDownloadManager notification --
//--------------------------------------------------------------//

- (int)_indexOfDownloadItem:(SRDownloadItem*)item
{
    if (!item) {
        return NSNotFound;
    }
    
    return [[[NSClassFromString(@"SRDownloadManager") sharedInstance] items] indexOfObject:item];
}

- (void)downloadDidBegin:(NSNotification*)notification
{
    // Reload data
    [_tableView reloadData];
}

- (void)downloadDidReceiveResponse:(NSNotification*)notification
{
}

- (void)_downloadDidEnd:(NSNotification*)notification
{
    // Remove progress indicator
    [[[notification object] downloadItem] setProgressIndicator:nil];
    
    // Reload data
    [_tableView reloadData];
}

- (void)downloadDidFinish:(NSNotification*)notification
{
    [self _downloadDidEnd:notification];
}

- (void)downloadDidFail:(NSNotification*)notification
{
    [self _downloadDidEnd:notification];
}

- (void)downloadStatusChanged:(NSNotification*)notification
{
    // Get index of download item
    int index;
    index = [self _indexOfDownloadItem:[[notification object] downloadItem]];
    if (index == NSNotFound) {
        return;
    }
    
    // Notify row height change
    [_tableView noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndex:index]];
}

//--------------------------------------------------------------//
#pragma mark -- NSTableView data source --
//--------------------------------------------------------------//

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return [[[NSClassFromString(@"SRDownloadManager") sharedInstance] items] count];
}

- (id)tableView:(NSTableView*)tableView 
        objectValueForTableColumn:(NSTableColumn*)tableColumn 
        row:(int)row
{
    // Get items
    NSArray*    items;
    items = [[NSClassFromString(@"SRDownloadManager") sharedInstance] items];
    if ([items count] < row) {
        return nil;
    }
    SRDownloadItem* item;
    item = [items objectAtIndex:row];
    
    // Get identifier
    id  identifier;
    identifier = [tableColumn identifier];
    
    // For title
    if ([identifier isEqualToString:@"title"]) {
        return item;
    }
    // For status
    if ([identifier isEqualToString:@"status"]) {
        return item;
    }
    // For date
    if ([identifier isEqualToString:@"date"]) {
        NSString*   dateStr;
        dateStr = [[item valueForKey:@"date"] description];
        return dateStr;
    }
    
    return nil;
}

//--------------------------------------------------------------//
#pragma mark -- NSTableView delegate --
//--------------------------------------------------------------//

- (void)tableViewSelectionDidChange:(NSNotification*)notification
{
    // Update appearance
    [self _updateLowerView];
}

//--------------------------------------------------------------//
#pragma mark -- NSTableViewEx delegate --
//--------------------------------------------------------------//

- (NSMenu*)tableView:(NSTableView*)tableView menuForEvent:(NSEvent*)event
{
    // Get download context menu
    NSMenu* menu;
    menu = [SRDownloadContextMenu contextMenu];
    
    return menu;
}

//--------------------------------------------------------------//
#pragma mark -- HMMenuButton delegate --
//--------------------------------------------------------------//

- (NSMenu*)menuButton:(HMMenuButton*)menuButton menuForEvent:(NSEvent*)event
{
    // Get download context menu
    NSMenu* menu;
    menu = [SRDownloadContextMenu contextMenu];
    
    return menu;
}

@end
