/**
 * @file input.c
 * @brief Input functions
 * 
 */
 
#include "io.h"
#include "thread.h"
#include "int.h"
#include "errnums.h"


thread_t input_queue;

/**
 * @brief Check for character in the keyboard buffer availible
 * @return EWOULDBLOCK on empty keyboard buffer, EOK else
 * 
 */
int getc_try (void){
	char key;
	if (kbd_buffer_empty() == EEMPTY) {
		return EWOULDBLOCK;
	}
	else {
		kbd_buffer_getc(&key);
		return(key);
	}
}

/**
 * @brief Reads char from keyboard buffer, else blocks calling thread and waits for keypress
 * @return character from keyboard buffer
 * 
 */
int getc (void){
	char key;
	mutex_lock(&keyboard_mtx);
	while (!kbd_buffer_getc(&key)) {
			cond_wait(&keyboard_cnd, &keyboard_mtx); 
	}

	mutex_unlock(&keyboard_mtx);
	return key;	
}


/**
 * @brief Read at most len-1 characters from keyboard, reading is terminated by '\n' 
 * character
 * @param str - null terminated returned string
 * @param len - maximum length of str buffer
 * @return EINVAL for len equal to 0, else str length (without trailing zero) 
 * 
 */
int gets(char * str, const size_t len) {
	int character = 0;
	int str_length = 0;
	if (!len)
		return EINVAL;
	else {
		while ((str_length < len-1) && (character != '\n')) {
			character = getc();
			str_length++;
			*str++ = character;
		}
		return str_length;
		*(str) = 0;
	}	
	
}
