/*
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;
    }
    
    // Register notification
    NSNotificationCenter*   center;
    center = [NSNotificationCenter defaultCenter];
    [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];
    
    // Configure array controller
    NSSortDescriptor*   sortDescriptor;
    sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:YES];
    [_downloadArrayController setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];
}

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

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

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

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

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

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

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

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

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

- (int)numberOfRowsInTableView:(NSTableView*)tableView
{
    return 0;
}

- (id)tableView:(NSTableView*)tableView 
        objectValueForTableColumn:(NSTableColumn*)tableColumn row:(int)rowIndex
{
    return nil;
}

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

static float    _tableRowHeight = 40;
static float    _tableRowWithProgressBarHeight = 56;

- (float)tableView:(NSTableView*)tableView heightOfRow:(int)row
{
    // Get download item
    SRDownloadItem* item;
    item = [[_downloadArrayController arrangedObjects] objectAtIndex:row];
    if (!item) {
        return _tableRowHeight;
    }
    
    // Check status
    switch ([[item valueForKey:@"status"] intValue]) {
    case SRDownloadStatusNone:
    case SRDownloadStatusPaused:
    case SRDownloadStatusCompleted:
    case SRDownloadStatusError:
    case SRDownloadStatusUnknown: {
        return _tableRowHeight;
    }
    }
    
    return _tableRowWithProgressBarHeight;
}

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

- (void)downloadStatusChanged:(NSNotification*)notification
{
    // Get download item
    SRDownloadItem* item;
    item = [[notification object] downloadItem];
    if (!item) {
        return;
    }
    
    // Get index of download item
    int index;
    index = [[_downloadArrayController arrangedObjects] indexOfObject:item];
    if (index == NSNotFound) {
        return;
    }
    
    // Notify row height change
    [_downloadTable noteHeightOfRowsWithIndexesChanged:[NSIndexSet indexSetWithIndex:index]];
}

//--------------------------------------------------------------//
#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
