import R from 'ramda';
import parseInt from 'lodash/parseInt';

var _require = require('lofi'),
    parseElement = _require.parseElement;

var rejectEmptyStrings = require('./rejectEmptyStrings');

var addChildTo = R.curry(function (element, parent) {
	return R.mergeWith(R.concat, parent, {
		children: [element]
	});
});

var prefixAndBodyRegex = /^([0-9]?[-0-9.]*[-.])?\s*(.*)$/;
var orderedPrefixRegex = /^[0-9]/;

export var parseInput = R.pipe(R.split('\n\n'), // sections
R.map(R.pipe(R.split('\n'), // elements
rejectEmptyStrings, // must have content
R.reduce(function (items, itemInput) {
	var _R$tail = R.tail(R.match(prefixAndBodyRegex, itemInput)),
	    prefix = _R$tail[0],
	    body = _R$tail[1]; // just get captured


	if (body == null) {
		return items;
	}

	var element = parseElement(body);

	// Skip #research
	if (element.tags.research) {
		return items;
	}

	var isChild = prefix != null;
	if (isChild) {
		if (items.length === 0) {
			var ordered = R.test(orderedPrefixRegex, prefix);
			return [{
				text: null,
				tags: { list: true, ordered: ordered },
				references: [],
				children: [element]
			}];
		} else {
			return R.adjust(addChildTo(element), -1, items);
		}
	} else {
		return R.concat(items, element);
	}
}, []))), R.reject(R.isEmpty));