'use strict';

const chalk = require('chalk');


/**
 * Indent the specified lines, and then join them.
 *
 * @param  {Array<string>} lines
 * @return {string}
 */
function indentAndJoinLines(lines) {

    return lines.map(line => ' '.repeat(8) + line).join('\n');

}

/**
 * Format a Blame message object.
 *
 * @param  {Object} msg
 * @return {string}
 */
function formatBlameMessage(msg) {

    let lines = [
        chalk.cyan(msg.path + ':' + msg.line),
        chalk.yellow(msg.context)
    ];

    const indent = ' '.repeat(msg.start - 1);
    const type   = msg.descr;

    if (msg.endline === msg.line) {
        // Single line of source code
        const marker = '^'.repeat((msg.end - msg.start) + 1);
        lines.push(indent + chalk.magenta(marker + ' ' + type));
    } else {
        // Multiple lines of source code
        lines.push(indent + chalk.magenta('^ ' + type));
    }

    return indentAndJoinLines(lines);

}

/**
 * Format a Comment message object.
 *
 * @param  {Object} msg
 * @return {string}
 */
function formatCommentMessage(msg) {

    const lines = [
        chalk.red(msg.descr)
    ];

    return indentAndJoinLines(lines);

}

/**
 * Format a Flow error object.
 *
 * @param  {Object} err
 * @return {string}
 */
function formatFlowErrorObject(err) {

    const formattedLines = err.message.map(function (msg) {
        switch (msg.type) {
            case 'Blame':
                return formatBlameMessage(msg);
            case 'Comment':
                return formatCommentMessage(msg);
            default:
                throw new Error('Unrecognised error message: ' + msg);
        }
    });

    return formattedLines.join('\n\n');

}

module.exports = formatFlowErrorObject;

@@ -276,16 +276,38 @@
  Format 
+an Operation block or 
 a Blame 
@@ -306,38 +306,37 @@
 a Blame message 
-object
+block
 .%0A *%0A * @param  
@@ -336,35 +336,37 @@
 param  %7BObject%7D 
-msg
+block
 %0A * @return %7Bstr
@@ -389,32 +389,38 @@
 n format
-BlameMessage(msg
+OperationOrBlame(block
 ) %7B%0A%0A   
@@ -453,19 +453,21 @@
 lk.cyan(
-msg
+block
 .path + 
@@ -472,19 +472,21 @@
 + ':' + 
-msg
+block
 .line),%0A
@@ -506,19 +506,21 @@
 .yellow(
-msg
+block
 .context
@@ -559,19 +559,21 @@
 .repeat(
-msg
+block
 .start -
@@ -596,19 +596,21 @@
 ype   = 
-msg
+block
 .descr;%0A
@@ -618,19 +618,21 @@
     if (
-msg
+block
 .endline
@@ -636,19 +636,21 @@
 ine === 
-msg
+block
 .line) %7B
@@ -727,21 +727,25 @@
 at((
-msg
+block
 .end - 
-msg
+block
 .sta
@@ -1011,22 +1011,21 @@
 message 
-object
+block
 .%0A *%0A * 
@@ -1041,19 +1041,21 @@
 Object%7D 
-msg
+block
 %0A * @ret
@@ -1093,27 +1093,22 @@
 tComment
-Message(msg
+(block
 ) %7B%0A%0A   
@@ -1142,19 +1142,21 @@
 alk.red(
-msg
+block
 .descr)%0A
@@ -1477,19 +1477,23 @@
 rmat
-BlameMessag
+OperationOrBlam
 e(ms
@@ -1564,15 +1564,8 @@
 ment
-Message
 (msg

rename functions and parameters