/* All Rights reserved */


#import "ExpDocument.h"


@implementation ExpDocument

- (void) dealloc
{  
	RELEASE(ledger);  
	[[NSNotificationCenter defaultCenter] removeObserver: self];  
	[super dealloc];
}

- (id) init
{  
	if( (self = [super init]) )
		{  
			ledger = [[LedgerModel alloc] init];
			filter = [[NSMutableDictionary alloc] initWithObjectsAndKeys: @"NONE", @"categories",
																																		@"NONE", @"dateFrom",
																																		@"NONE", @"dateTo",
																																		@"NONE", @"item", nil];
			
			[[NSNotificationCenter defaultCenter] addObserver: self
																							 selector: @selector(updateTotal:)
																							     name: @"Total Changed"
																							   object: nil];

			[[NSNotificationCenter defaultCenter] addObserver: self
      			                                   selector: @selector(inputPanelDayChanged:)
                                                   name: @"Day Changed"                                       
                                                 object: nil];

      [[NSNotificationCenter defaultCenter] addObserver: self
                                               selector: @selector(updateFilter:)   
                                                   name: @"Filters Changed"
                                                 object: nil];                                                 
      return self;
		}  
	return nil;
}


// Instance methods
//******************


- (void) inputPanelDayChanged: (NSNotification *) not
{
  if (self == [[NSDocumentController sharedDocumentController] currentDocument])
    {
      [ledger setDefaultDate: [not object]];
    }
}

- (void) updateTotal: (NSNotification *) aNotification
{
	if (self == [[NSDocumentController sharedDocumentController] currentDocument])
		{
			[total setStringValue: [[ledger total] stringValue]];
            [average setStringValue: [[ledger average] stringValue]];
		}
}

- (void) updateFilter: (NSNotification *) aNotification
{
	if( self == [[NSDocumentController sharedDocumentController] currentDocument] )
		{
			ASSIGN(filter, [aNotification object]);
			[ledger filterRecords: filter];
			[tableView reloadData];
		}
}

- (void) addEntry: (id) sender
{
	NSMutableDictionary *tempDict;
	
	tempDict = [NSMutableDictionary new];
	[tempDict setObject: [[ledger defaultDate] descriptionWithCalendarFormat: @"%d.%m.%Y"] forKey: @"date"];
	[tempDict setObject: [[ledger defaultDate] descriptionWithCalendarFormat: @"%Y%m%d"] forKey: @"dateSortable"];
	[ledger addRecord: tempDict];
	[ledger filterRecords: filter];
	[tableView reloadData];
	NSLog(@"test1");
	[tableView editColumn: 1 row: [ledger newRecord] withEvent: nil select: YES];
	//[ledger clearNewRecord];
	[self updateChangeCount: NSChangeDone];
}
				

// NSDocument override methods
//*****************************


- (NSData *) dataRepresentationOfType: (NSString *) type
{
  if ([type isEqualToString: @"expense"])
    return [[[ledger records] description] dataUsingEncoding: NSASCIIStringEncoding];
  else
    return nil;
}

- (BOOL) loadDataRepresentation: (NSData *) data ofType: (NSString *) type
{
	NSString *string = [[NSString alloc] initWithData: data encoding: NSASCIIStringEncoding];
  
  if( [type isEqualToString: @"expense"] && string != nil )
  	{
  		if( [string rangeOfString: @"<?xml"].length > 0 )
  			{
  				string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
  			}
  			
			[ledger setRecords: [string propertyList]];
			[filter setObject: [ledger categories] forKey: @"categories"];
			[ledger filterRecords: filter];

			RELEASE(string);
			return YES;
    }
  return NO;
}

- (void) windowControllerDidLoadNib: (NSWindowController *) controller
{
  NSTableColumn *column;
  NSCell *cell;
//	NSNumberFormatter *formatter;
	
  column = [[tableView tableColumns] objectAtIndex: 0];
  [column setWidth: 90];
  [column setEditable: NO];
  [column setResizable: NO];
  [column setIdentifier: @"date"];
  [[column headerCell] setFont: [NSFont boldSystemFontOfSize: 12]];
  [[column headerCell] setStringValue: _(@"Date")];
  
  column = [[NSTableColumn alloc] initWithIdentifier: @"category"];
  [column setWidth: 100];
  [column setEditable: YES];
  [column setResizable: NO];
  [[column headerCell] setStringValue: _(@"Category")];
  [tableView addTableColumn: column];
  
  column = [[NSTableColumn alloc] initWithIdentifier: @"item"];
  [column setWidth: 289];
  [column setEditable: YES];
  [column setResizable: YES];
  [[column headerCell] setStringValue: _(@"Item")];
  [tableView addTableColumn: column];
  
  column = [[NSTableColumn alloc] initWithIdentifier: @"amount"];
  [column setWidth: 80];
  [column setEditable: YES];
  [column setResizable: NO];
  cell = [[NSCell alloc] initTextCell: @""];
  [cell setAlignment: NSRightTextAlignment];

// NSNumberFormatter isn't fully implemented yet.

//  formatter = [[NSNumberFormatter alloc] init];
//  [formatter setFormat:@"#,##0.00"];
//  [cell setFormatter: formatter];
//  RELEASE(formatter);

  [column setDataCell: cell];
  RELEASE(cell);
  [[column headerCell] setStringValue: _(@"Amount")];
  
  [tableView addTableColumn: column];

  RELEASE(column);

  [tableView setAutoresizesAllColumnsToFit: YES];
  [tableView setDataSource: ledger];
  [tableView registerForDraggedTypes: [NSArray arrayWithObjects: NSGeneralPboardType, nil]];

	[totalLabel setStringValue: _(@"Total")];
	[averageLabel setStringValue: _(@"Daily Average")];
	[defaultDateButton setTitle: _(@"Set Default Date")];
	
  [total setStringValue: [[ledger total] stringValue]];
  [average setStringValue: [[ledger average] stringValue]];
	
  [[[self windowControllers] objectAtIndex: 0] setShouldCloseDocument: YES];
}

- (NSString *) windowNibName
{
  return @"ExpDocument";
}


// NSWindow delegate methods
//***************************


- (void) windowDidBecomeKey: (NSNotification *)aNotification
{
	// when the following if statement is uncommented, it will fail when switching between document windows within
	// the application. It will return true if selecting a document window when another app is in the 
	// foreground, and in some cases when switching between an NSDocument window, and another window (eg filters) 
	// within the app. You can see this happen if you uncomment the NSLogs.
	
//	NSLog(@"1 - recieved the notification");
//	if (self == [[NSDocumentController sharedDocumentController] currentDocument])
//		{
//		NSLog(@"2 - will send some notifications");
      [[NSNotificationCenter defaultCenter] postNotificationName: @"Dates Changed" object: [ledger dates]];
      [[NSNotificationCenter defaultCenter] postNotificationName: @"Categories Changed" object: [ledger categories]];
      [[NSNotificationCenter defaultCenter] postNotificationName: @"Selections Changed" object: filter];      	 		
//	 	}
}	


@end
