const asciiArt = require('ascii-art')
const log = require('./logging')

async function displayTable (format, data, filteredFields, columnWidths) {
  if (format === 'json') {
    const displayJson = JSON.stringify(data, null, 2)
    log.plain(displayJson)
  } else {
    let rows = data.map(d => {
      return filteredFields.map(field => {
        // Not perfect, but this is to avoid the [object Object] scenario for json fields in DB
        return typeof d[field] === 'object' && d[field] !== null
          ? JSON.stringify(d[field])
          : d[field]
      })
    })

    if (format === 'csv') {
      log.plain(filteredFields.join(','))
      rows.forEach(row => console.log(row.join(',')))
    } else {
      if (columnWidths) {
        // for each column specified, pad all values in column till they are that width
        // TODO: Change this to specify a minimum width that is based on header
        columnWidths.forEach(columnWidth => {
          rows = rows.map(row => {
            row[columnWidth.column] = row[columnWidth.column].padEnd(columnWidth.width)
            return row
          })
        })
      }

      asciiArt.table({
        data: rows,
        columns: filteredFields
      }, result => log.plain(result))
    }
  }
}

module.exports = { displayTable }
