// Hacker news stories

var fetcher = require("../fetcher");
var Story = require("../models/Story");
var async = require("async");

var topUrl = "https://hacker-news.firebaseio.com/v0/topstories.json";
var itemBaseUrl = "https://hacker-news.firebaseio.com/v0/item/";
var sourceName = "hn";

exports.getTop10 = function(callback) {
	var tasks = {
		getTopStories: function(done) {
			getTopStories(topUrl, done);
		},
		sliceStories: ["getTopStories", function(done, results) {
			var sliced;
			if (results.getTopStories.length >= 10) {
				sliced = results.getTopStories.slice(0,9);
			} else {
				sliced = results.getTopStories;
			}
			done(null, sliced);
		}],
		getItems: ["sliceStories", function(done, results) {
			getItems(results.sliceStories, done);
		}],
		formatItems: ["getItems", function(done, results) {
			formatItems(results.getItems, done);
		}]
	};

	async.auto(tasks, function(err, results) {
		if (err) {
			callback(err);
			return;
		}

		callback(null, results.formatItems);
	});
};

// Retrives IDs of top stories
function getTopStories(url, callback) {
	fetcher.getJSONByUrl(url, callback);
}

// Requests details for each item ID in items
function getItems(items, callback) {
	async.map(items, getItemDetailsById, callback);
}

function getItemDetailsById (item, callback) {
	var url = itemBaseUrl + item + ".json";
	fetcher.getJSONByUrl(url, callback);
}

function formatItems(items, callback) {
	var formattedItems = [];
	for (var i = 0; i < items.length; i = i + 1) {
		formattedItems.push(new Story({
			title: items[i].title,
			url: items[i].url,
			source: sourceName
		}));
	}

	callback(null, formattedItems);
}