var Config = require('./config.js');
var Commands = require('./commands.js');
var SkyChat = require('node-redsky').init(Config);
Commands.init(SkyChat, Config);

function Rollbot()
{
	this.reset();
	this.toBank = 'rollbot';

	SkyChat.on('command', Commands.execute.bind(Commands));
	SkyChat.on('connected_list', this.onUpdate.bind(this));
	SkyChat.on('rand', this.win.bind(this));

	SkyChat.on('log_once', (function() {
		setInterval(this.watch.bind(this), 1000);
	}).bind(this));

	SkyChat.on('newmessage', this.handleMessage.bind(this));
	SkyChat.on('server_info', this.handleMessage.bind(this));
}

Rollbot.prototype.bet = function(user, amount) {
	if(amount === 0) return;
	if(typeof this.bets[user] === 'undefined') this.bets[user] = 0;
	this.bets[user] += amount;
	this.stake += amount;

	let pourcent = this.bets[user] / this.stake * 100;
	pourcent = pourcent.toFixed(2);

	SkyChat.sendLater(user + ' a misé ' + this.bets[user] + '₭ (soit ' + pourcent + '% du total) :-)');

	if(!this.rolling && this.stake >= 100 &&
		 Object.keys(this.bets).length >= 2) {
		this.rolling = true;
		this.rollTime = Date.now() + 60000;
	} else if(amount >= 98) {
		this.rollTime += 10000;
	}
};

Rollbot.prototype.checkForBank = function(msg) {
	if(msg.pseudo == 'Banque' && msg.message.indexOf('a donn') != -1) {
		let giveMsg = msg.message.match(/(.*?) a.*; (\d+)₭ &.*; (.*?) /);
		if(!giveMsg) {
			console.log('give message invalide');
			console.log(msg.message);
			return;
		}

		// If coins were given to rollbot
		if(giveMsg[3].toLowerCase() == Config.username.toLowerCase()) {
			this.bet(giveMsg[1].trim(), parseFloat(giveMsg[2]));
		}
	}
};

Rollbot.prototype.getSeconds = function() {
	return Math.floor((this.rollTime - Date.now()) / 1000);
};

Rollbot.prototype.handleMessage = function(msg) {
	console.log(SkyChat.messageHandler.format(msg));
	this.checkForBank(msg);
};

Rollbot.prototype.onUpdate = function(data) {
	for (var i in data.list) {
		if (data.list[i].pseudo_lower == Config.username.toLowerCase()) {
			this.points = data.list[i].points;
			break;
		}
	}
};

Rollbot.prototype.reset = function() {
	this.bets = [];
	this.stake = 0;
	this.rollTime = Number.MAX_VALUE;
	this.importantBet = false;
	this.rolling = false;
};

Rollbot.prototype.roll = function()
{
	var rng = Math.random();
	var num = 0, time = 0;
	var msg = 'ROLL ! :ok:';

	this.oldBets = [];
	this.oldStake = this.stake;

	for (var i in this.bets) {
		msg += ' $$$$ :d) ' + i + ' : ' + num + ' - ';
		num += this.bets[i];
		msg += num + ' (' + (this.bets[i] / this.stake * 100).toFixed(2) + '%)';
		this.oldBets[i] = num;
	}

	SkyChat.send(msg);

	// Rolling for winner
	SkyChat.sendLater('/rand 0 ' + num, 500);

	// Ready for next roll
	this.reset();
};

Rollbot.prototype.watch = function()
{
	if(!this.importantBet && this.rolling) {
		if(this.getSeconds() <= 0) {
			this.roll();
		} else if(this.getSeconds() % 30 === 0) {
			SkyChat.send(this.getSeconds() + ' secondes avant un roll :bave:');
		}
	}
};

// When a roll has been read
Rollbot.prototype.win = function(rand)
{
	if(rand.pseudo != Config.username) return;
	var oldNum = 0;

	for (var i in this.oldBets) {
		var num = this.oldBets[i];
		if(num >= rand.number) {
			var mise = num - oldNum;
			var chance = (mise / this.oldStake * 100).toFixed(2);
			var msg = 'Et le gagnant est... :2d) ' + i + ' :2g) avec ' + chance + '% de chance de gagner ';
			if(mise >= 10000) {
				msg += ':widance:';
			} else {
				msg += ':-)))';
			}

			SkyChat.sendLater(msg, 1000);

			if(i != Config.username.toLowerCase()) {
				SkyChat.sendLater(`/mp banque !tip ${i} ${this.oldStake}`, 2000);
			}

			break;
		}

		oldNum = num;
	}
};

global.rollbot = new Rollbot();

