/* TSConsoleTextShelfItem.m created by tsengel on Fri 15-Aug-1997 */

#import "TSConsoleTextShelfItem.h"

@implementation TSConsoleTextShelfItem

- (id)initWithContentsOfFile:(NSString *)aString
{
    id  contentDict;

    self = [super initWithContentsOfFile:aString];
    if( !self) return nil;

    // <<HACK>> evil...

    [NSBundle loadNibNamed:@"ConsoleTextShelf" owner:self];

    // If we don't have a path then lets set a default title..according to our default file...

    if( !aString ) [self setTitle:@"Console"];

    // Ok...now read which file we should monitor...if there is no info available we'll
    // go for the defualt console.log.

    contentDict = [NSDictionary dictionaryWithContentsOfFile:[[self path] stringByAppendingPathComponent:@"Info.plist"]];

    monitoredFile = [[contentDict objectForKey:@"MonitoredFilePath"] retain];
    if( !monitoredFile )
    {
        // Ok..put in the default path to the console log and note that we need to save our stuff.

        monitoredFile = @"/tmp/console.log";
        unsavedChanges = YES;
    }
    return self;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];

    [ourFileHandle closeFile];
    [ourFileHandle release];
    [super dealloc];
}

- (void)ok:(id)sender
{
    shouldUpdateAutomatically = NO;

    [super ok:self];

    // Seems like we are swapping away.. lets disable all these periodic updates...we are no longer interested
    // in being up to date.

    // NSLog( @"Unregistering from path log tracking etc.. blah.");

    // [[NSNotificationCenter defaultCenter] removeObserver:self];
    // this is a <<HACK>>  !!!!  We will miss all the data which has been read after this operation... hmm..
}

- (void)revert:(id)sender
{
    // Load the monitored file into the view !

    id		someData;

    [super revert:self];

    // NSLog( @"Registering from path log tracking etc.. blah.");

    // If we never loaded the file..now its about time to do so...

    shouldUpdateAutomatically = YES;

    if( !ourFileHandle )
    {
        [textView setString:@""];
        ourFileHandle = [[NSFileHandle fileHandleForUpdatingAtPath:monitoredFile] retain];

        someData = [ourFileHandle readDataToEndOfFile];
        [self _appendTextData:someData];

        // No matter what was before... from now one we want to be informed about changes !!

        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(newDataAvailable:)
                                                     name:NSFileHandleReadCompletionNotification
                                                   object:ourFileHandle];
    }
    [self updateLog:self];
}

- (void)save
{
    id		basePath = [self path];
    id		ourFileDict = [NSMutableDictionary new];

    [super save];

    // Just make a note which file we did monitor..that.s all we need.

    basePath = [basePath stringByAppendingPathComponent:@"Info.plist"];

    [ourFileDict setObject:@"ConsoleTextShelf" forKey:@"ShelfType"];
    [ourFileDict setObject:monitoredFile forKey:@"MonitoredFilePath"];
    [ourFileDict writeToFile:basePath atomically:YES];
}

- (void)newDataAvailable:(NSNotification *)notification
{
    id		newData = [[notification userInfo] objectForKey:NSFileHandleNotificationDataItem];

    if( newData ) [self _appendTextData:newData];
}

- (void)_appendTextData:(NSData *)newData
{
    id aNewString  = [[[NSString alloc] initWithData:newData encoding:NSASCIIStringEncoding] autorelease];

    // Append the newString and scroll the new stuff to visible...
    // if for some strange reason we have no string... put in a message!!

    if( !aNewString ) aNewString = [NSString stringWithFormat:@"ATTENTION: Problems with log file at path %@.\nPlease check access permissions and path.\n\n", monitoredFile];

    [textView appendString:aNewString];
    [textView scrollRangeToVisible:NSMakeRange( [[textView string] length], 0 )];
}

- (void)updateLog:(id)sender
{
    // Ok.. this does not really clear the log...but updates it right now... brr...I know..
    // <<HACK>> Ugly... until we know 

    [ourFileHandle readInBackgroundAndNotify];

    if( shouldUpdateAutomatically )
        [NSTimer scheduledTimerWithTimeInterval:5
                                         target:self
                                         selector:@selector(updateLog:)
                                         userInfo:nil
                                         repeats:NO];
}

- (void)clearLog:(id)sender
{
    // Ok.. this does not really clear the log...but updates it right now... brr...I know..

    // Ok..we frist should take teh files attributes and then set the same attributes again.. and if we are not allowed to
    // write it we should pop up an allter etc..pp. well...
    //.. maybe we should just truncate our internal representation but not the rela file...

    [textView setString:@""];
}

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

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

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

@end
