/* Run a command, with buffered output to a text object. */

#import <stdio.h>
#import <appkit/TextField.h>
#import <appkit/Panel.h>
#import "Reporter.h"
#import "Subprocess.h"

int strlen(char *s);
char *strcpy(char *s1, char *s2);
int strcmp(char *s1, char *s2);
char *malloc(unsigned u);
char *realloc(char *b, unsigned u);
void free(char *b);
int system(char *cmd);
char *getname(int uid);
int getuid();


/* ====================================================================== */
@implementation Reporter

/* ---------------------------------------------------------------------- */
/* Refresh display, by running the command. */
- refresh:sender
{
    outputBuffer= NULL;
    if (!text) {
	printf("Reporter: nowhere to put output!\n");
    }
    if (!process) {
	process= [Subprocess new]; /* first time--make new process object */
    }
    [process init:command withDelegate:self andPtySupport:NO andStdErr:YES];
    return self;
}

/* ---------------------------------------------------------------------- */
/* Return the command that we run when we refresh. */
- (char*)command
{
   return command;
}

/* ---------------------------------------------------------------------- */
/* Set the command to be run; make copy of command string if asked to. */
- setCommand:(char*)cmd andCopy:(BOOL)yesno
{
   if (yesno) {
       command= malloc(strlen(cmd)+1);
       strcpy(command,cmd);
   } else {
       command= cmd;
   }
   return self;
}

/* ---------------------------------------------------------------------- */
/* Set the command to be run. */
- setCommand:(char*)cmd
{
    return [self setCommand:cmd andCopy:NO];
}

/* ---------------------------------------------------------------------- */
/* Return the text object that we display into. */
- text
{
   return text;
}

/* ---------------------------------------------------------------------- */
/* Set the text object that we will display into. */
- setText:(id)txt
{
    text= txt;
    return self;
}

/* ====================================================================== */
/* Subprocess Delegation */

/* ---------------------------------------------------------------------- */
/*  Buffer the output from the process. */
-subprocessOutput:(char *)buffer
{
    if (outputBuffer) {
	outputBuffer=
	   realloc(outputBuffer,strlen(outputBuffer)+strlen(buffer)+2);
    } else {
	outputBuffer= malloc(strlen(buffer)+1);
	outputBuffer[0]= '\0';
    }
    strcpy(outputBuffer+strlen(outputBuffer), buffer);
    return self;
}

/* ---------------------------------------------------------------------- */
/* Deal with end of subprocess: display buffered output. */
- subprocessDone
{
    if (outputBuffer) {
        [text setStringValue:outputBuffer];
	free(outputBuffer);
	outputBuffer= NULL;
    } else {
	[text setStringValue:""];
    }
    return self;
}

@end
