/*
SRDownloadController.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 "SRAppController.h"
#import "SRDownloader.h"
#import "SRDownloadController.h"
#import "SRDownloadManager.h"

#import "SRDownloadStatusCell.h"

#import "SRDownloadContextMenu.h"

// Frame auto save name
NSString*   SRDwonloadPanelFrameAutoSaveName = @"SRDownloadPanelFrameAutoSaveName";

@implementation SRDownloadController

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

+ (id)sharedInstance
{
    static SRDownloadController*    _sharedInstance = nil;
    if (!_sharedInstance) {
        _sharedInstance = [[SRDownloadController alloc] init];
    }
    
    return _sharedInstance;
}

- (id)init
{
    self = [super initWithWindowNibName:@"DownloadPanel"];
    if (!self) {
        return nil;
    }
    
    // Initialize instance variables
    _isOpendInternally = NO;
    
    // 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)awakeFromNib
{
    // Configure window
    NSWindow*   window;
    window = [self window];
    [window setFrameAutosaveName:SRDwonloadPanelFrameAutoSaveName];
    
    // Set download status cell
    NSTableColumn*          column;
    NSCell*                 oldCell;
    HMImageTextFieldCell*   cell;
    column = [_downloadTable tableColumnWithIdentifier:@"progress"];
    oldCell = [column dataCell];
    cell = [[SRDownloadStatusCell alloc] init];
    [cell setFont:[oldCell font]];
    [column setDataCell:cell];
    [cell release];
    
    // Configure menu button
    [_menuButton setDelegate:self];
}

- (void)dealloc
{
    // Remove observer
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [super dealloc];
}

//--------------------------------------------------------------//
#pragma mark -- Opening --
//--------------------------------------------------------------//

- (void)setOpendInternally:(BOOL)flag
{
    _isOpendInternally = flag;
}

//--------------------------------------------------------------//
#pragma mark -- Show window --
//--------------------------------------------------------------//

- (void)showWindowAndFadeOut
{
    // Show window
    [self showWindow:self];
    
    // Start fade out timer
    [(HMBlkPanel*)[self window] resetFadeOutTimer];
}

//--------------------------------------------------------------//
#pragma mark -- Persistent stack --
//--------------------------------------------------------------//

- (NSManagedObjectContext*)managedObjectContext
{
    return [[SRAppController sharedInstance] managedObjectContext];
}

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

- (void)pauseDownloadAction:(id)sender
{
    // Get selected row
    int row;
    row = [_downloadTable selectedRow];
    if (row == -1) {
        return;
    }
    
    // Get selected download item
    NSArray*        activeItems;
    SRDownloadItem* downloadItem;
    activeItems = [[SRDownloadManager sharedInstance] activeItems];
    if ([activeItems count] <= row) {
        return;
    }
    downloadItem = [activeItems objectAtIndex:row];
    
    // Pause download
    [[SRDownloadManager sharedInstance] pauseDownloadForItem:downloadItem];
}

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

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

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

- (void)deleteDownloadAction:(id)sender
{
#if 0
    // Delete items
    NSEnumerator*   enumerator;
    id              item;
    enumerator = [items objectEnumerator];
    while (item = [enumerator nextObject]) {
        [[SRDownloadManager sharedInstance] removeDownloadForItem:item];
    }
#endif
}

- (void)showShelfAction:(id)sender
{
    [[SRAppController sharedInstance] openShelf:@"jp.hmdt.shiira.downloadshelf"];
}

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

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return [[[SRDownloadManager sharedInstance] activeItems] count];
}

- (id)tableView:(NSTableView*)tableView 
        objectValueForTableColumn:(NSTableColumn*)tableColumn 
        row:(int)row
{
    // Get active items
    NSArray*    activeItems;
    activeItems = [[SRDownloadManager sharedInstance] activeItems];
    if ([activeItems count] < row) {
        return nil;
    }
    
    // Get identifier
    id  identifier;
    identifier = [tableColumn identifier];
    
    // For icon
    if ([identifier isEqualToString:@"icon"]) {
        return [[activeItems objectAtIndex:row] icon];
    }
    // For progress
    if ([identifier isEqualToString:@"progress"]) {
        return [activeItems objectAtIndex:row];
    }
    
    return nil;
}

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

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

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

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

- (void)_downloadDidEnd:(NSNotification*)notification
{
    // Remove progress indicator
    [[[notification object] downloadItem] setBlkProgressIndicator:nil];
    
    // Reload data
    [_downloadTable reloadData];
    
    // Close window automatically
    if (_isOpendInternally) {
        if ([[[SRDownloadManager sharedInstance] activeItems] count] == 0) {
            // Start fade out timer
            [(HMBlkPanel*)[self window] resetFadeOutTimer];
        }
    }
}

- (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
    [_downloadTable noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndex:index]];
}

//--------------------------------------------------------------//
#pragma mark -- NSWindow delegate --
//--------------------------------------------------------------//

- (void)windowWillClose:(NSNotification*)notification
{
    _isOpendInternally = NO;
}

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

- (NSMenu*)tableView:(NSTableView*)outlineView 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
