#include "file_upload.h"

using namespace std;
using namespace cgi_tools;

//
// Simple program to test the MultipartRequest class.
//
// Author:	Matthew W. Coan
// Date:	April 14, 2002
//
int
main()
{
	// Set the content type of our response
	fprintf(stdout, "Content-type: text/plain\r\n\r\n");
	fflush(stdout);
	
	// This processes the multipart request
	MultipartRequest req("files");
	
	// Check for error
	if(req.errorCode() == MultipartRequest::NO_ERROR) {
		// Print out the element names
		for(size_t i = 0; i < req.size(); i++) {
			fprintf(stdout, "req[%d]=\"%s\"\n",i,req[i]->name());
			fflush(stdout);
		}
		fprintf(stdout, "\n");
		fflush(stdout);
		
		// Get a pointer to the data file element
		MultipartRequest::FormElement * pElement = req["dataFile"];
		
		// Die if the data file was not found
		if(!pElement) {
			fprintf(stdout, "dataFile not found!");
			fflush(stdout);
			exit(0);
		}
		
		// Die if the data file element was not a file
		if(!pElement->fileName()) {
			fprintf(stdout, "dataFile is not a file!");
			fflush(stdout);
			exit(0);
		}
		
		// Print out the data file elements information
		fprintf(stdout, "Uploaded File:\n");
		fprintf(stdout, "name: \"%s\"\n", pElement->name());
		fprintf(stdout, "fileName: \"%s\"\n", pElement->fileName());
		fprintf(stdout, "localFileName: \"%s\"\n", pElement->localFileName());
		fprintf(stdout, "type: \"%s\"\n", pElement->type());
		fprintf(stdout, "length: \"%d\"\n\n", pElement->length());
		fflush(stdout);
		
		// Get a pointer to the text1 form element
		pElement = req["text1"];
		
		// Die if not found
		if(!pElement) {
			fprintf(stdout, "text1 not found!");
			fflush(stdout);
			exit(0);
		}
		
		// Print out text1's information
		fprintf(stdout, "Form Data:\n");
		fprintf(stdout, "name: \"%s\"\n", pElement->name());
		fprintf(stdout, "data: \"%s\"\n", pElement->data());
		fprintf(stdout, "length: \"%d\"\n\n", pElement->length());
		fflush(stdout);
		
		// Get a pointer to the text2 form element
		pElement = req["text2"];
		
		// Die if not found
		if(!pElement) {
			fprintf(stdout, "text2 not found!");
			fflush(stdout);
			exit(0);
		}
		
		// Print out text2's information
		fprintf(stdout, "name: \"%s\"\n", pElement->name());
		fprintf(stdout, "data: \"%s\"\n", pElement->data());
		fprintf(stdout, "length: \"%d\"\n\n", pElement->length());
		fflush(stdout);
	}
	// Handle the error
	else {
		switch(req.errorCode()) {
			case MultipartRequest::IO_ERROR:     // I/O error occured
				fprintf(stdout, "IO_ERROR");
				fflush(stdout);
				break;
			case MultipartRequest::PARSE_ERROR:  // Multipar request parse error
				fprintf(stdout, "PARSE_ERROR");
				fflush(stdout);
				break;
			case MultipartRequest::MAX_UPLOAD:   // Maximum file upload size
				fprintf(stdout, "MAX_UPLOAD");
				fflush(stdout);
				break;
			case MultipartRequest::CGI_ERROR:    // CGI error
				fprintf(stdout, "CGI_ERROR");
				fflush(stdout);
				break;
		}
	}

	return 0;
}

