/*
 * shell_commands.c
 *
 *  Created on: Aug 11, 2016
 *      Author: tkl
 */
#include <stdbool.h>
#include <stddef.h>
#include <string.h>

#include "list.h"
#include "driver.h"
#include "shell_data.h"
#include "shell.h"
#include "version.h"
#include "shell_commands.h"

static void *cmd_kosmos_version_cb(const char *cmd);
static void *cmd_list_all_commands_cb(const char *cmd);
static void *cmd_echo_on_cb(const char *cmd);
static void *cmd_echo_off_cb(const char *cmd);

struct command cmd_kosmos_version = {
		.command = "kname",
		.description = "Print current kosmos version.",
		.command_callback = cmd_kosmos_version_cb
};

struct command cmd_list_all_commands = {
		.command = "ls",
		.description = "List all installed commands.",
		.command_callback = cmd_list_all_commands_cb
};

struct command cmd_echo_on = {
		.command = "echo on",
		.description = "Switch echo on.",
		.command_callback = cmd_echo_on_cb
};

struct command cmd_echo_off = {
		.command = "echo off",
		.description = "Switch echo off.",
		.command_callback = cmd_echo_off_cb
};


static void *cmd_kosmos_version_cb(const char *cmd)
{
	char *greeter = "Kosmos Version: ";

	drv_write(shell_object.shell_device, greeter, strlen(greeter));
	drv_write(shell_object.shell_device, KERNEL_VERSION, strlen(KERNEL_VERSION));
	drv_write(shell_object.shell_device, ".", 1);
	drv_write(shell_object.shell_device, MAJOR_VERSION, strlen(MAJOR_VERSION));
	drv_write(shell_object.shell_device, ".", 1);
	drv_write(shell_object.shell_device, MINOR_VERSION, strlen(MINOR_VERSION));
	drv_write(shell_object.shell_device, ".", 1);
	drv_write(shell_object.shell_device, BUILD_NUMBER, strlen(BUILD_NUMBER));
	return NULL;
}

static void *cmd_list_all_commands_cb(const char *cmd)
{
	char *greeter = "Command list: \r\n";
	struct list_node *it = shell_object.command_list.front;
	int i, len = list_get_len(&shell_object.command_list);

	drv_write(shell_object.shell_device, greeter, strlen(greeter));
	for(i = 0; i < (len - 1); i++) {
		if(NULL != it) {
			struct command *command = (struct command *)it->data;
			drv_write(shell_object.shell_device, command->command, strlen(command->command));
			drv_write(shell_object.shell_device, " - ", 3);
			drv_write(shell_object.shell_device, command->description, strlen(command->description));
			drv_write(shell_object.shell_device, "\r\n", 2);
			it = it->next;
		}
	}

	return NULL;
}

static void *cmd_echo_on_cb(const char *cmd)
{
	shell_object.echo_on = true;
	return NULL;
}
static void *cmd_echo_off_cb(const char *cmd)
{
	shell_object.echo_on = false;
	return NULL;
}
