/* Unix version of soccer client		*/
/* updated 8/8/03						*/
/* Dan Maynes-Aminzade <monzy@mit.edu>	*/

#include "soccerclient.h"

int main(int argc, char* argv[])
{
	int sockfd;
	struct sockaddr_in their_addr; // connector's address information
	struct hostent *he;
	int numbytes;

	if (argc != 2) {
		fprintf(stderr,"usage: soccerclient hostname\n");
		return 0;
	}

    if ((he=gethostbyname(argv[1])) == NULL) {  // get the host info
        perror("gethostbyname");
		return 0;
    }

    if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1) {
        perror("socket");
		return 0;
    }

    their_addr.sin_family = AF_INET;     // host byte order
    their_addr.sin_port = htons(REMOTE_PORT); // short, network byte order
    their_addr.sin_addr = *((struct in_addr *)he->h_addr);
    memset(&(their_addr.sin_zero), '\0', 8); // zero the rest of the struct

	PLAYER myplayers[5];	// stores local player state
	for (int i=0; i<NUM_PLAYERS; i++) {
		myplayers[i].vx = 0.0;
		myplayers[i].vy = 0.0;
		myplayers[i].kick = 0.0;
	}

	setup_terminal();
	printf("Use your keyboard to control the game:\n");
	printf("1-5: Select Player\nUp,Down,Left,Right: Change Velocity\nSpacebar: Kick\nq: Quit\n\n");

	int c;
	int currentplayer = 0;

	while ((c!=0x51)&&(c!=0x71)) {
		c = getchar(); 
		switch(c) {
			case 0x31: currentplayer=0; break;
			case 0x32: currentplayer=1; break;
			case 0x33: currentplayer=2; break;
			case 0x34: currentplayer=3; break;
			case 0x35: currentplayer=4; break;

			case 0x41: //up
				myplayers[currentplayer].vy -= 1.0;
				break;
			case 0x42: //down
				myplayers[currentplayer].vy += 1.0;
				break;
			case 0x43: //right
				myplayers[currentplayer].vx += 1.0;
				break;
			case 0x44: //left
				myplayers[currentplayer].vx -= 1.0;
				break;
			case 0x20: //space
				myplayers[currentplayer].kick = 3.0;

		}
		// now compose datagram and send update
		DATAGRAM d;
		d.team = htonl(1);
		for (int i=0; i<NUM_PLAYERS; i++) {
			d.team1[i].vx = htonf(myplayers[i].vx);
			d.team1[i].vy = htonf(myplayers[i].vy);
			d.team1[i].kick = htonf(myplayers[i].kick);
			myplayers[i].kick = 0.0;
		}
		if ((numbytes=sendto(sockfd, ((char*)&d), sizeof(DATAGRAM), 0,
				(struct sockaddr *)&their_addr, sizeof(struct sockaddr))) == -1) {
			perror("sendto");
			return 0;
		}
//	    printf("sent %d bytes to %s\n", numbytes, inet_ntoa(their_addr.sin_addr));
	}
	restore_terminal();
	close(sockfd);
    return 0;
}

void setup_terminal() {
	/* setup terminal for interactive keyboard control */
	tcgetattr(fileno(stdin), &original_t); 
	new_t = original_t; 
	/* turn off input and echo */ 
	new_t.c_lflag &= ~(ICANON | ECHO); 
	/* set new attributes */ 
	tcsetattr(fileno(stdin), TCSAFLUSH, &new_t); 
	fflush(stdin); 
}

void restore_terminal() {
	tcsetattr(fileno(stdin), TCSANOW, &original_t); 
}
