/* ARISA - Text only functions for arisa-sh
 * Copyright (C) 2003, 2004 Carl Ritson
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */

static char *lreadline(FILE *fp, char *buffer, size_t size) {
	int i,ret;
	for(i = 0; i < (size - 1); ++i) {
		ret = fgetc(fp);
		if(ret != EOF && ret != '\n')
			buffer[i] = (char) ret;
		else
			break;
	}
	buffer[i] = '\0';
	if(i != 0)
		return buffer;
	else
		return NULL;
}

static void console_print(const char *msg) {
	if(timestamp) {
		struct tm 	timeval;
		char		tsbuf[32];
		time_t 		now = time(NULL);
		
		localtime_r(&now,&timeval);
		if(timestamp == 2)
			strftime(tsbuf,sizeof(tsbuf),"%T",&timeval);
		else
			strftime(tsbuf,sizeof(tsbuf),"%R",&timeval);
		printf("[%s] %s\n",tsbuf,msg);
	} else
		printf("%s\n",msg);
}

static int console_main(void) {
#define KBD 0
#define SOK 1
	char buffer[512],linebuf[128],*line;
	struct pollfd pfd[2];
	int ret;
	
	pfd[KBD].fd	= fileno(stdin);
	pfd[KBD].events	= POLLIN;
	pfd[SOK].fd	= sok;
	pfd[SOK].events	= POLLIN;
	
	for(;;) {
		pfd[KBD].revents = 0;
		pfd[SOK].revents = 0;
		
		ret = poll(pfd,2,-1);
		if(ret == -1)
			break;
		
		if(pfd[KBD].revents & POLLIN) {
			line = lreadline(stdin,linebuf,sizeof(linebuf));
			if(line != NULL) {
				ret = sprintf(buffer,"%s\r\n",linebuf);
				ret = send(sok,buffer,ret,0);
				if(ret == -1)
					break;
			}
		}
		
		if(pfd[SOK].revents & (POLLERR | POLLHUP | POLLNVAL)) {
			ret = -1;
			break;
		} else if(pfd[SOK].revents & POLLIN) {
			do {
				ret = recv_line(buffer,sizeof(buffer));
				if(ret > 0) {
					console_print(buffer);
				} else
					break;
			} while(has_pending_data(sok) > 0);
			if(ret == -1)
				break;
		}
	}
	if(ret == -1 && errno != 0)
		perror("Socket Error");

	return 0;
#undef KBD
#undef SOK
}
