/*
 * This menu cell is a cell in the weather menu browser.
 * Knows how to transmit codes and fetch bits of text,
 * which is somewhat special-cased for this service.
 * M. J. Hawley
 * mike@media-lab.mit.edu
 * Copyright (c) November 1991, MIT Media Laboratory.
 */
#import "MyMenuCell.h"
#import "Process.h"
#import <string.h>
#import <ctype.h>

@implementation  MyMenuCell

char *getLabel(), *getSend(), *getGet(), *curMenuFirst(), *curMenuLast();
extern char *curMenu, *path();
extern int Verbose;

void
Say(a,b,c,d,e) char *a, *b, *c, *d, *e; {
    char s[1024];
    sprintf(s,a,b,c,d,e);
    setText(s);
}

- click:sender {
    if (*send == '!'){ // run a command
        char t[1024], *p = send+1, *s;
        *t = '\0'; sscanf(send+1,"%s",t);
        if (*t && (s = path(t))){
            p += strlen(t);
            System("%s %s &",s,p);
        } else
            System("%s &",send+1);
        setText("\nThat request is running quietly in the background.");
        return self;
    } else
    if (*send == '|'){ // read from a pipe
        char t[1024], *p = send+1, *s, ff[1024];
        FILE *f;
        *t = '\0'; sscanf(p,"%s",t);
        if (*t && (s = path(t))){
            p += strlen(t);
            sprintf(ff,"%s %s",s,p);
        } else
            sprintf(ff,"%s",p);
        if (f=popen(ff,"r")){
            char buf[120000], *b = buf;
            *b = '\0';
            Say("\ntrying: %s...", ff);
            while (fgets(b,sizeof b,f))
                b += strlen(b);
            pclose(f);
            setText(buf);
        } else
            setText("\nCouldn't fetch that data.");
        return self;
    } else
    if (*send == '<'){ // open a file
        char *p = send+1;
        if (*p == '<'){ // ... via workspace
            openFile(path(p+1));
        } else
            setFile(p); // ... locally
        return self;
    } else if (*send)
        ensurelogin(), Put("%s",send);
    if ([self isLeaf]) setFetchText(label);
    if (strcmp("text",get)==0){
        char buf[80000];
        getReport(buf);
        if (*buf) setText(buf);
    }
    return self;
}

- click2:sender {
    return self;
}

- setStringValueNoCopy:(char *)s {
    label = getLabel(s);
    send = getSend(s);
    get = getGet(s);
    [super setStringValue:label];
    [self setLeaf:state(get)?NO:YES];
    //[self setAction:@selector(click:)];
    [self setTarget:self];
    return self;
}

- setStringValue: (char *)s {
    return [self setStringValueNoCopy:s];
}

- (char *)stringValue {
    return label;
}

- (char *)get {
    return get;
}

- send {
    Put("%s",send);
    return self;
}

- mouseDown:(NXEvent *)e {
	[super mouseDown:e];
        if (e->data.mouse.click == 1){
                [self click:self];
        }
}

@end	