/* -*-objc-*-
 */

#include <float.h>
#include <stdio.h>

#import "MyDelegate.h"

#import "RSSReaderToolbarDelegate.h"
#import "SplitDelegate.h"
#import "HTTPFetcher.h"

#import "RSSArticle.h"

@implementation MyDelegate

- (void) dealloc
{
  RELEASE(toolbar);
  RELEASE(window);
  RELEASE(tableView);
  RELEASE(splitView);
  RELEASE(scrollView);
  
  RELEASE(articleView);
  
  RELEASE(feedColumn);
  RELEASE(headlineColumn);
  RELEASE(dateColumn);
  
  RELEASE(myStoreFile);
  
  RELEASE(myFeeds);
  
  [super dealloc];
}



- (void) saveStatus: (id)sender
{
  [NSArchiver
    archiveRootObject: [self RSSFeeds]
    toFile: [self storeFile]];
}



- (void) applicationWillFinishLaunching: (NSNotification*) not
{
 /* Create Menu */
  
  // This is included here just for MacOSX debugging reasons.
 /*
   NSMenu *menu;
   NSMenu *info;

   menu = [NSMenu new];
   [menu addItemWithTitle: @"Info"
                   action: NULL
            keyEquivalent: @""];
   [menu addItemWithTitle: @"Hide"
                   action: @selector(hide:)
            keyEquivalent: @"h"];
   [menu addItemWithTitle: @"Quit"
                   action: @selector(terminate:)
            keyEquivalent: @"q"];

   info = [NSMenu new];
   [info addItemWithTitle: @"Info Panel..."
                   action: @selector(orderFrontStandardInfoPanel:)
            keyEquivalent: @""];
   [info addItemWithTitle: @"Preferences"
                   action: NULL 
            keyEquivalent: @""];
   [info addItemWithTitle: @"Help"
                   action: @selector (orderFrontHelpPanel:)
            keyEquivalent: @"?"];

   [menu setSubmenu: info 
            forItem: [menu itemWithTitle:@"Info"]];
   RELEASE(info);

   [NSApp setMainMenu:menu];
   RELEASE(menu);
   */
  [self buildMenu];
  
  // for MacOSX debugging reasons: this line will crash the application
  //[[NSMenu new] initWithTitle: @"a" action:nil keyEquivalent:nil];
  [self buildWindow];
}



- (void) addStandardFeeds
{
  RSSFeedList * feeds;
  RSSFeed * feed;
  
  feeds = [self RSSFeeds];
  feed =
    [ [RSSFeed alloc] initWithFetcher:
			[ [HTTPFetcher alloc]
			  initWithURL:@"http://slashdot.org/slashdot.rss"
			  ]
      ];
  
  if ([feed fetch])
    {
      printf ("\n :-(  Error when getting feeds...\n\n");
    }
  
  [feeds addFeed: feed];
  
  
  feed =
    [ [RSSFeed alloc] initWithFetcher:
			[ [HTTPFetcher alloc]
			  initWithURL:@"http://erdferkel.blogger.de/rss"
			  ]
      ];
  
  if ([feed fetch])
    {
      printf ("\n :-(  Error when getting feeds...\n\n");
      }
    
  [feeds addFeed: feed];
  
  RELEASE(feed);
}


- (void) initRSSFeeds
{
  [self RSSFeeds];  
}


- (void) reloadTable
{
  [tableView reloadData];
}


#define BROWSER "dillo"
#define HOMEPAGE @"http://www.unix-ag.uni-kl.de/~guenther/rssreader.html"
- (void) openHomepage: (id) sender
{
#ifdef MACOSX
  [[NSWorkspace sharedWorkspace]
    openURL: [NSURL URLWithString: HOMEPAGE]];
#else
  if (!fork())
    execlp(BROWSER, BROWSER, [HOMEPAGE cString], NULL);
#endif
}

#define TOP    600
#define RIGHT  500

- (void) buildWindow
{
  NSRect winRect;
  
  [self initRSSFeeds];
  
  winRect = NSMakeRect ( 100, 100, RIGHT, TOP );
  
  unsigned int styleMask =
    NSTitledWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask;
  
  window = [[NSWindow alloc]
	     initWithContentRect: winRect
	     styleMask: styleMask
	     backing: NSBackingStoreBuffered
	     defer: NO];
  
  [window setTitle: @"RSS Reader"];
  [window setDelegate: self];
  
  
  // TOOLBAR
  toolbar = [[NSToolbar alloc]
	      initWithIdentifier: @"RSSWindowToolbar"];
  [toolbar setDelegate: [[RSSReaderToolbarDelegate alloc] init]];
  [toolbar setVisible: YES];
  [toolbar setAllowsUserCustomization: YES];
  [toolbar setAutosavesConfiguration: YES];
  
  
  // SPLIT VIEW
  splitView = [ [NSSplitView alloc]
		initWithFrame: NSMakeRect(5, 5, RIGHT-10, TOP-10) ];
  [splitView setVertical: NO];
  [splitView setDelegate: [[SplitDelegate alloc] init]];
  
  
  
  // TABLE COLUMNS
  feedColumn = [[NSTableColumn alloc] initWithIdentifier: @"feedcol"];
  [feedColumn setEditable: NO];
  [feedColumn setMinWidth: 50];
  [feedColumn setResizable: YES];
  [[feedColumn headerCell] setStringValue: @"Feed"];
  [[self RSSFeeds] feedCol: feedColumn];
  
  headlineColumn = [[NSTableColumn alloc] initWithIdentifier: @"headlinecol"];
  [headlineColumn setEditable: NO];
  [headlineColumn setMinWidth: 300];
  [headlineColumn setResizable: YES];
  [[headlineColumn headerCell] setStringValue: @"Headline"];
  [[self RSSFeeds] headlineCol: headlineColumn];
  
  dateColumn = [[NSTableColumn alloc] initWithIdentifier: @"datecol"];
  [dateColumn setEditable: NO];
  [dateColumn setMinWidth: 40];
  [dateColumn setResizable: YES];
  [[dateColumn headerCell] setStringValue: @"Date"];
  [[self RSSFeeds] dateCol: dateColumn];
  
  
  // TABLE
  tableView = [ [NSTableView alloc]
		initWithFrame: NSMakeRect(5,5, 200,400) ];
  [tableView setDataSource: [self RSSFeeds]];
  [tableView setDelegate: [self RSSFeeds]];
  
  [tableView addTableColumn: feedColumn];
  [tableView addTableColumn: headlineColumn];
  [tableView addTableColumn: dateColumn];
  
  // SCROLLVIEW
  scrollView = [[NSScrollView alloc]
		 initWithFrame: NSMakeRect(0,0,300,300)];
  [scrollView setHasVerticalScroller: YES];
  [scrollView setHasHorizontalScroller: NO];
  [scrollView setBorderType: NSBezelBorder];
  
  // ARTICLE
  articleView = [[NSButton alloc] initWithFrame: NSMakeRect(10,10,100,100)];
  [articleView setTitle: @"Go to RSS Reader homepage"];
  [articleView setTarget: self];
  [articleView setAction: @selector(openHomepage:)];
  
  
  // --------------------------------------------------------
  
  // CONSTRAINTS
  [scrollView setAutoresizingMask: (NSViewWidthSizable|NSViewHeightSizable)];
  [splitView setAutoresizingMask: (NSViewWidthSizable|NSViewHeightSizable)];
  
  // PUTTING THINGS TOGETHER
  
  [window setToolbar: toolbar];
  [[window contentView] addSubview: splitView];
  {
    [splitView addSubview: scrollView];
    {
      [scrollView setDocumentView: tableView];
    }
    
    [splitView addSubview: articleView];
  }
  
  // RELEASING WIDGETS
  // none to release here
}


// replaces the articleView with a new one.
- (void) setArticle: (RSSArticle*) article
{
  NSTextStorage* descStorage;
  NSLayoutManager* descLMan;
  NSTextContainer* descTextContainer;
  NSTextView* descriptionField;
  NSRect r;
  NSView * documentView;
  NSString * content;
  
  
  id oldArticleView;
  float width, height;
  
  oldArticleView = articleView;
  // ARTICLE SCROLLVIEW
  articleView = [[NSScrollView alloc]
		  initWithFrame: NSMakeRect(0,0,300,300)];
  [articleView setHasVerticalScroller: YES];
  [articleView setHasHorizontalScroller: NO];
  [articleView setBorderType: NSBezelBorder];
  
  // calculate content
  content =
    [[NSString alloc]
      initWithFormat: @"%@\n%@",
      [article headline], [article description] ];
  
  // build description field
  descStorage = [[NSTextStorage alloc]
		  initWithString: content];
  RELEASE(content);
  
  descLMan = [[NSLayoutManager alloc] init];
  [descStorage addLayoutManager: descLMan];
  RELEASE(descLMan);
  
  descTextContainer = [[NSTextContainer alloc] init];
  [descLMan addTextContainer: descTextContainer];
  
  descriptionField = [[NSTextView alloc] init];
  [descriptionField setTextContainer: descTextContainer];
  [descriptionField setDrawsBackground: NO];
  [descriptionField setEditable: NO];
  [descriptionField setSelectable: YES];
  [descriptionField setAlignment: NSLeftTextAlignment];
  [descriptionField setBackgroundColor: [NSColor whiteColor]];
  [descriptionField setDrawsBackground: YES];
  [descriptionField setTextContainerInset: NSMakeSize(5,5)];
  
  [descriptionField setFont:[NSFont boldSystemFontOfSize:18]
		    range:NSMakeRange(0,[[article headline] length])];
  
  r = [oldArticleView frame];
  width   = r.size.width;
  height  = r.size.height;
  
  // set frame for description field
  r.origin.x = 5;
  r.origin.y = 5;
  r.size.width = width - 30;
  r.size.height = height - (5+5+13+10);
  //[descriptionField setFrame: r];
  r.size.width  -=10;
  r.size.height -=10;
  [descTextContainer setContainerSize: NSMakeSize(r.size.width, FLT_MAX)];
  
  // ALIGNMENTS
  [articleView setAutoresizesSubviews: YES];
  [[articleView documentView] setAutoresizesSubviews: YES];
  
  // ALIGNMENT OF DESCRIPTION
  [descriptionField setVerticallyResizable: YES];
  [descriptionField setHorizontallyResizable: YES];
  [descriptionField
    setAutoresizingMask: (NSViewWidthSizable|NSViewHeightSizable)];
  [descriptionField setMinSize: NSMakeSize(0.0, 0.0)];
  [descriptionField setMaxSize: NSMakeSize(1E7, 1E7)];  
  [descTextContainer setTextView:descriptionField]; 
  [descTextContainer setWidthTracksTextView:YES];
  RELEASE(descTextContainer);
  
  [articleView setDocumentView: descriptionField];
  
  
  // PUTTING THINGS TOGETHER
  
  NSLog(@"documentView: %@", [[articleView documentView] description]);
  NSLog(@"contentView:  %@", [[articleView contentView] description]);

  [articleView setFrame: [oldArticleView frame]];
  [splitView replaceSubview: oldArticleView with: articleView];
  [splitView adjustSubviews];
  RELEASE(oldArticleView);
  
  // RELEASES
  RELEASE(descriptionField);
}


// FIXME: Here feeds may be loaded from a file.
- (RSSFeedList*) RSSFeeds
{
  NSLog(@"RSSFeeds called.");
  if (myFeeds == nil)
    {
      NSLog(@"myFeeds == nil");
      myFeeds =
      [[NSUnarchiver unarchiveObjectWithFile: [self storeFile]] retain];
      NSLog(@"loaded feed list %@", [myFeeds description]);
      
      if (myFeeds == nil)
	{
	  NSLog(@"Couldn't load feeds from file, creating a new one.");
	  myFeeds = [[RSSFeedList alloc] init];
	  
	  // FIXME: Remove this when the user can add feeds himself. :-]
	  [self addStandardFeeds];
	}
      
      // this means the setArticle: (RSSArticle*) method is called.
      [myFeeds setArticleViewer: self];
    }
  
  if (myFeeds == nil)
    NSLog(@"Couldn't initialize *any* feeds.");
  
  return myFeeds;
}


- (void) windowDidLoad: (NSNotification*) aNotification
{
  NSLog(@"windowDidLoad\n");
  //[window setToolbar: toolbar];
}


- (void) applicationDidFinishLaunching: (NSNotification*)not
{
  [window orderFront: nil];  
}


- (NSString*) storeFile
{
  if (myStoreFile == nil)
    {
      myStoreFile =
	[@"~/.rssreader-data" stringByExpandingTildeInPath];
      RETAIN(myStoreFile);
    }
  
  return myStoreFile;
}


- (void) buildMenu
{
  NSMenu *mainMenu;
  
  NSMenuItem * helpItem;
  NSMenu *helpMenu;
  
  // Help Menu
  
  helpMenu = [NSMenu new];
  
  [helpMenu addItemWithTitle: @"Info"
	    action: @selector(orderFrontStandardInfoPanel:)
	    keyEquivalent: @"x"];
  
  [helpMenu addItemWithTitle: @"Help"
	    action: @selector(orderFrontHelpPanel:)
	    keyEquivalent: @"?"];
  // Main Menu
  
  mainMenu = [NSMenu new];
  
  helpItem =
    [mainMenu addItemWithTitle: @"Help"
	      action: NULL
	      keyEquivalent: @"h"];
  
  [mainMenu setSubmenu: helpMenu
  	    forItem: [mainMenu itemWithTitle:@"Help"]];
  
  
  [mainMenu addItemWithTitle: @"Save feeds to disk"
	    action: @selector(saveStatus:)
	    keyEquivalent: @"s"];
    
  [mainMenu addItemWithTitle: @"Quit"
	    action: @selector(terminate:)
	    keyEquivalent: @"q"];
  
  

  [NSApp setMainMenu: mainMenu];
}


@end

