#import "IFileIconButton.h"
#import <appkit/Application.h>
#import "IMMEditor.h"
#import "Object1.h"
#import <libc.h>

// This object provides the icon for drag and drop from the editor.

@implementation IFileIconButton

static BOOL doubleClick;
static NXEvent theEvent;

// ## REWRITE! ## might be better to send a message than use extern
extern HashTable *listOfTempFiles;

- init
{
    [super init];
    return(self);
}

- mouseDown:(NXEvent *)event
{
    switch(event->data.mouse.click) {
    case 1:
        // drag and drop current representation of selection
        doubleClick = NO;
        theEvent = *event;
        [self perform:@selector(singleClickAction:) with:nil afterDelay:200
            cancelPrevious:YES];
        break;
    case 2:
        // toggle between alternate representations for selection
        doubleClick = YES;
        [super mouseDown:event];
        break;
    }
    return(self);
}

- (void)singleClickAction:dummy
// execute drag and drop
{
    const char *filename;
    char *copyOfFilename;
    NXRect rect;

    if (doubleClick == NO) {
        if ((filename = [[[self cell] target] getFilename:self]) != NULL) {
            copyOfFilename = NXCopyStringBuffer(filename);
            rect.origin.x = rect.origin.y = 0.0;
            rect.size.width = rect.size.height = 48.0;
            [self dragFile:filename fromRect:&rect slideBack:YES
                event:&theEvent];
            [[[[self cell] target] text] setOwnerOfDraggedIconToMe:YES];
            // ## REWRITE! ## very bad to use externs
            [listOfTempFiles insertKey:copyOfFilename value:nil];
            [IFileIconButton perform:@selector(unlink:) with:(id)copyOfFilename
                afterDelay:600000 cancelPrevious:NO];
        }
    }
}

+ (void)unlink:filename
// delete temporary files.  Really messy since it is not possible to predict
// when workspace manager is finish using the temporary files.
{
    char command[512];

    sprintf(command, "rm -r %.505s", (const char *)filename);
    system(command);
    [listOfTempFiles removeKey:filename];
    free((char *)filename);
}

@end



