'use strict';

var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);

app.use(express.static(__dirname + '/public'));

var argv = require('yargs')
	.usage('Usage: -p [port]')
	.default('p', 5000)
	.argv;

var gameCounter = 0;
var used = [];
var games = {};
var chats = {};

function handleGame (game) {
	var gameID = used.shift();
	if (!gameID || games[gameID]) {
		gameID = ++gameCounter;
	}
	game.gameID = gameID;

	game.on('disconnect', function () {
		disconnectGame(gameID);
		console.log(chats);
		used.push(gameID);
		delete games[gameID];
	});

	games[gameID] = game;
	game.emit('gameID', gameID);
}

// Handle all the connections
io.on('connection', function (socket) {
	socket.on('type', function (msg) {
		if (msg === 'game') {
			handleGame(socket);
		} else {
			socket.disconnect();
		}
	});
});

http.listen(argv.p, function(){
	console.log('Server listening on port', argv.p);
});


//====================
//=== TELEGRAM BOT ===
//====================
var TelegramBot = require('node-telegram-bot-api');
var token = '<BOT:TOKEN>';

var bot = new TelegramBot(token, {polling: true});

var MESSAGE_HELP = [
"/connect [ID] - connect to a specific game.",
"/help - Display this."
].join("\n");

bot.onText(/\/help/, function(msg){
	bot.sendMessage(msg.chat.id, MESSAGE_HELP);
});

// Validate Game Connection
function valGameConn(chatID){
	console.log(chats);
	if(!chats[chatID]){
		bot.sendMessage(chatID, "This chat isn't connected to a game yet. /help");
		return false;
	}
	return true;
}

bot.onText(/\/connect (.+)/, function(msg, match){
	var chatID = msg.chat.id;
	var gameID = match[1];
	if(games[gameID]){
		bot.sendMessage(chatID, "Successfully connected to game: '" + gameID + "'\n/join to hop in!");
		chats[chatID] = gameID;
		console.log(chats);
	}else{
		bot.sendMessage(chatID, "Couldn't connect to a game with the ID: '"+gameID+"' because it doesn't exist!");
	}
});

bot.onText(/\/join/, function(msg){
	var chatID = msg.chat.id;

	if(!valGameConn(chatID))return;

	var gameID = chats[chatID];
	var user = msg.from;
	games[gameID].emit('addPlayer', user);

	var opts = {
		reply_markup: JSON.stringify({
			keyboard: [
				["JUMP"]
			],
		})
	};
	bot.sendMessage(msg.chat.id, user.username + ", sacrifice yourself for the gods!", opts);	
});

bot.onText(/JUMP/, function(msg){
	var chatID = msg.chat.id;

	if(!valGameConn(chatID))return;

	var gameID = chats[chatID];
	var user = msg.from;
	games[gameID].emit('jump', user);
});

var disconnectGame = function(gameID){
	Object.keys(chats).forEach(function(chatID){
		if(chats[chatID] == gameID){
			chats[chatID] = null;
			bot.sendMessage(chatID, "Disconnected from game! /help")
		}
	});
}

