
#import "Controller.h"
#import "RSSHandler.h"
#import "FeedWindow.h"
#import "DictionaryAdditions.h"
#import "StringAdditions.h"
#import "ColorAsRGBADictionary.h"
#import "HeadlineView.h"

@implementation FeedWindow

static int _count = 0;
#define MAX_OFFSET     10
#define WINDOW_SHIFT   40
#define WINDOW_BASE_X 100
#define WINDOW_BASE_Y 700
#define MARGIN         10

- initWithTickerWindow:(TickerWindow *)twin
{
    ticker = twin;
    RETAIN(ticker);

    articles = [twin articles];
    TEST_RETAIN(articles);

    NSDictionary *attr = [twin attributes];
    font =
	[NSFont 
	    fontWithName:[attr objectForKey:ATTR_FONTNAME]
	    size:[attr floatForKey:ATTR_FONTSIZE]];
    TEST_RETAIN(font);

    fg = [NSColor colorFromRGBADictionary:[attr objectForKey:ATTR_FG]];
    bg = [NSColor colorFromRGBADictionary:[attr objectForKey:ATTR_BG]];

    RETAIN(fg);
    RETAIN(bg);

    NSRect frame;

    frame.origin.x = WINDOW_BASE_X 
	+ (_count % MAX_OFFSET)*WINDOW_SHIFT;
    frame.origin.y = WINDOW_BASE_Y -FEEDWINDOW_HEIGHT 
	- ((_count / MAX_OFFSET) % MAX_OFFSET)*WINDOW_SHIFT;
    frame.size.width = FEEDWINDOW_WIDTH;
    frame.size.height = FEEDWINDOW_HEIGHT;
    _count++;

    [super 
	initWithContentRect:frame
	styleMask:(NSResizableWindowMask | 
		   NSClosableWindowMask | NSTitledWindowMask)
	backing:NSBackingStoreRetained 
	defer:NO];
    [self setMinSize:NSMakeSize(FEEDWINDOW_WIDTH, FEEDWINDOW_HEIGHT)];
    
    frame.origin.x = MARGIN;
    frame.origin.y = MARGIN;

    frame.size.width  -= 2*MARGIN;
    frame.size.height -= 2*MARGIN;

    NSSplitView *split =
	[[NSSplitView alloc] initWithFrame:frame];
    AUTORELEASE(split);
    [split setDelegate:self];

    [split setAutoresizingMask:
               NSViewWidthSizable | NSViewHeightSizable];
    
    frame.size.height /= (float)2.0;
    frame.origin.y += frame.size.height;

    headlines = [[NSBrowser alloc] initWithFrame:frame];
    AUTORELEASE(headlines);
    [headlines setHasHorizontalScroller:NO];
    [headlines setMaxVisibleColumns:1];
    [headlines setAllowsMultipleSelection:NO];
    [headlines setTitled:NO];
    [headlines setDelegate:self];
    [headlines setTarget:self];
    [headlines setAction:@selector(setArticle:)];

    [headlines setMenu:[HeadlineView defaultMenu]];

    NSCell *proto = [headlines cellPrototype];
    NSFont *cfont = [proto font], *nfont;

    NSFontManager *fm = [NSFontManager sharedFontManager];

    float fsize = [cfont pointSize]+2.0;
    while(fsize<=48.0 && 
	  (nfont = [fm convertFont:cfont toSize:fsize])==cfont){
	fsize++;
    }
    
    [proto setFont:nfont];
    [headlines setCellPrototype:proto];

    [headlines loadColumnZero];

    [split addSubview:headlines];

    frame.origin.y -= frame.size.height;
    
    NSScrollView *scrollView =
	[[NSScrollView alloc] initWithFrame:frame];
    AUTORELEASE(scrollView);

    [scrollView setHasHorizontalScroller:NO];
    [scrollView setHasVerticalScroller:YES]; 
    [scrollView setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
    [[scrollView contentView] 
	setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];
    [[scrollView contentView] setAutoresizesSubviews:YES];

    // Build up the text network
    NSRect textRect = [[scrollView contentView] frame];
    content = [[NSTextView alloc] initWithFrame:textRect];
    AUTORELEASE(content);

    [content setEditable:NO];

    [content setHorizontallyResizable:NO];
    [content setVerticallyResizable:YES];

    [content setMinSize:NSMakeSize(0, 0)];
    [content setMaxSize:NSMakeSize(1E7, 1E7)];
    [content setAutoresizingMask: NSViewHeightSizable | NSViewWidthSizable];

    [[content textContainer] 
	setContainerSize:NSMakeSize(frame.size.width, 1E7)];
    [[content textContainer] setWidthTracksTextView:YES];

    [content setMenu:[HeadlineView defaultMenu]];

    [content setRichText:YES];
    [content setUsesFontPanel:NO];

    [content setBackgroundColor:bg];
    [content setTextColor:fg];

    [scrollView setDocumentView:content];

    [split addSubview:scrollView];

    [[self contentView] addSubview:split];
    [self 
	setTitle:
	    [NSString stringWithFormat:@"%@ (%d)",
		      [twin title], _count]];

    [[NSNotificationCenter defaultCenter]
	addObserver:self
	selector:@selector(tickerDidUpdate:)
	name:TickerDidUpdateNotification object:twin];
    [[NSNotificationCenter defaultCenter]
	addObserver:self
	selector:@selector(tickerWindowWillClose:)
	name:NSWindowWillCloseNotification object:twin];

    int where = [twin currentArticleIndex];
    [headlines selectRow:where inColumn:0];
    [headlines sendAction];

    // [self setBackgroundColor:bg];
    
    [self setHidesOnDeactivate:YES];
    [self setReleasedWhenClosed:YES];

    return self;
}

- (int)browser:(NSBrowser *)sender numberOfRowsInColumn:(int)column
{
    if(articles==nil){
	return 0;
    }

    return [articles count];
}


- (void)browser:(NSBrowser *)sender willDisplayCell:(id)cell 
	  atRow:(int)row column:(int)column;
{
    GenericArticle *art = [articles objectAtIndex:row];
    NSString *atitle =
	[[[art title]
	     stringFromFirstLine]
	    stringByTrimmingWhitespaceAndNewlines];

    [cell setStringValue:atitle];
    [cell setLeaf:YES];
}

- setArticle:(id)sender
{
    int what = [sender selectedRowInColumn:0];

    [content
	replaceCharactersInRange:
	    NSMakeRange(0, [[content string] length])
	withAttributedString:
	    [[articles objectAtIndex:what]
		contentWithTitleFont:font
		foreground:fg background:bg]];

    return self;
}


- (float)splitView:(NSSplitView *)sender 
constrainMinCoordinate:(float)proposedMin ofSubviewAt:(int)offset
{
    return [sender frame].size.height/6;
}

- (float)splitView:(NSSplitView *)sender 
constrainMaxCoordinate:(float)proposedMax ofSubviewAt:(int)offset
{
    return [sender frame].size.height*5/6;
}


- (void)tickerDidUpdate:(NSNotification *)aNotification
{
    TickerWindow *twin = [aNotification object];
    ASSIGN(articles, [twin articles]);
    NSLog(@"%@ updated articles", self);

    [self setTitle:[twin title]];
    [headlines loadColumnZero];
    [content setString:@""];
}

- (void)tickerWindowWillClose:(NSNotification *)aNotification;
{
    [self close];
}

- articleText:(id)sender
{
    int what = [headlines selectedRowInColumn:0];
    [ticker setExternalChoice:what];

    [ticker articleText:self];
    return self;
}

- articleBrowse:(id)sender
{
    int what = [headlines selectedRowInColumn:0];
    [ticker setExternalChoice:what];

    [ticker articleBrowse:self];
    return self;
}

- articleLink:(id)sender
{
    int what = [headlines selectedRowInColumn:0];
    [ticker setExternalChoice:what];

    [ticker articleLink:self];
    return self;
}

- articleShowAll:(id)sender
{
    NSBeep();
    return self;
}

- articleUpdate:(id)sender
{
    if([ticker loadInProgress]==YES){
	NSBeep();
	return self;
    }

    [ticker refresh];
    return self;
}


- (void)dealloc
{
    NSLog(@"dealloc %@", self);

    RELEASE(ticker);

    TEST_RELEASE(articles);
    TEST_RELEASE(font);

    RELEASE(fg);
    RELEASE(bg);
    
    [super dealloc];
}

@end

