var restify = require('restify');
var builder = require('botbuilder');
var orderRepository = new (require('./repo.js'))();
var interpret = require('./interpreter.js');
var commands = require('./interpreter-commands.js');
var OrderService = require('./order-service.js');

var orderService = new OrderService({
	clientId : process.env.CLIENT_ID,
	clientSecret : process.env.CLIENT_SECRET
}, {
	id : process.env.SPREADSHEET_ID,
	sheetName : process.env.SHEET_NAME
});

/*
 * Bot Setup
 */
var server = restify.createServer();
server.listen(process.env.port || process.env.PORT || 3978, function () {
   console.log('%s listening to %s', server.name, server.url); 
});
  
var connector = new builder.ChatConnector({
    appId: process.env.MICROSOFT_APP_ID,
    appPassword: process.env.MICROSOFT_APP_PASSWORD
});

var bot = new builder.UniversalBot(connector);
server.post('/api/messages', connector.listen());

/*
 * Bots Dialogs
 */
bot.dialog('/', function(session) {
	var message = {
			sender : {
				name: session.message.user.name,
				id: session.message.user.id
			},
			text: session.message.text,
			timeStamp: Date.now()
	};

	message.token = interpret(message);
	session.userData = message;
	session.beginDialog('/' + message.token.command);
	session.endDialog();
});

bot.dialog('/' + commands.ADD_ORDER, function(session){
	var user = session.userData.sender.name;
	var order = session.userData.token.payload || {};
	orderRepository.addOrder(user, order);
	session.send(formatOrderForUser(orderAsString(order),user));
	session.endDialog();
});

bot.dialog('/' + commands.HELP, function(session){
	session.send("for pancakes: nutnut, turella, ...");
	session.send("get total orders");
	session.send("submit order");
	session.endDialog();
});

bot.dialog('/' + commands.GET_TOTAL, function(session){
	session.send(formatTotalOrder(orderAsString(orderRepository.getOrders())));
	session.endDialog();
});

bot.dialog('/' + commands.SUBMIT_ORDER, [
	function(session) {
		console.log("submit order #1");
		var user = session.userData.sender.name;
		var order = session.userData.token.payload;
		if (!order) {
			session.send("No orders found");
		} else {
			orderService.submit(order, user, function promptForAuthCode(authUrl, onAuthCodeReceived){
				console.log("submit order - prompt for code callback");
				session.userData.authUrl = authUrl;
				session.userData.onCodeEntered = onAuthCodeReceived;
				session.beginDialog('/prompt-for-auth-code');
			});
		}
	}, function(session) {
		console.log("submit order #2");
		session.send("...");
		session.endDialog();
	}
]);

bot.dialog('/prompt-for-auth-code', [
	function(session) {
		console.log("prompt-for-auth-code #1");
		builder.Prompts.text(session, `Enter auth code from ${session.userData.authUrl}`);
	},
	function(session, results) {
		console.log("prompt-for-auth-code #2");
		console.log(`${JSON.stringify(results)}`);
		session.userData.onCodeEntered(null, results.response);
		session.endDialog();
	}
]);

bot.dialog('/' + commands.DONT_UNDERSTAND, function(session){
	session.send("I'm sorry, I'm not sure I understand what you are trying to say. Please try asking for help.");
	session.endDialog();
});

function orderAsString(order) {
	return Object.getOwnPropertyNames(order)
			.filter(function(flavor){
				return order[flavor] > 0;
			}).reduce(function(prev, flavor){
				return [prev, [order[flavor],"x",flavor].join(' ')].join(prev === "" ? "" : ", ");
			}, "");
}

function formatTotalOrder(orderAsString) {
	return orderAsString.length > 0 ?
		`Total order is ${orderAsString}` :
		"No orders so far";
}

function formatOrderForUser(orderAsString, userName) {
	return orderAsString.length > 0 ?
		`${userName} ordered ${orderAsString}.` :
		`${userName} ordered nothing so far.`;
}

/*

	return orderString.length === 0 ? "No orders so far." : `Total order is ${orderString}`;

*/

