#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>

#include "x10io.H"
#include "cli.H"



static TOKEN_TABLE actions [] = {
	{ X10_ON,	"on" },
	{ X10_OFF,	"off" },
	{ X10_BRIGHT,	"bright" },
	{ X10_BRIGHT,	"up" },
	{ X10_DIM,	"dim" },
	{ X10_DIM,	"down" },
	{ X10_LIGHTSON, "lightson" },
	{ X10_LIGHTSON, "lights on" },
	{ X10_LIGHTSOFF,"lightsoff" },
	{ X10_LIGHTSOFF,"lights off" },
	{ X10_ALLOFF,   "alloff" },
	{ X10_ALLOFF,   "all off" },
	{ X10_INVALID,	NULL}
};


int turn(int housecode, int unit, char **argv)
{
	int action = get_token (*argv, actions);
	int count = 1;
	if (action == X10_INVALID) {
		fprintf (stderr, "%s: Unknown action %s.\n",
			program_name, *argv);
		return (FAIL_PARSE);
	}

	argv++;
	if (*argv) {
		char *error;
		count = strtol (*argv, &error, 0);
		if (error && *error) {
			fprintf (stderr, "%s: Invalid count %s.\n",
				 program_name, *argv);
			exit (FAIL_PARSE);
		}
	}
	
	if (!unit && action == X10_ON)
		return (send_command (housecode, 0, X10_LIGHTSON, 1));

	if (!unit && action == X10_OFF)
		return (send_command (housecode, 0, X10_LIGHTSOFF, 1));

	if (action == X10_LIGHTSON || action == X10_LIGHTSOFF ||
	    action == X10_ALLOFF)
		return (send_command (housecode, 0, action, 1));
	
	if (!unit)
		return (FAIL_UNITNEEDED);

	return (send_command (housecode, unit, action,
		(action == X10_BRIGHT || action == X10_DIM) ? count : 1));
}

