const { table } = require('table')
const log = require('./logging')

async function displayTable (format = 'json', 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 ascii-art-table doesn't really like anything here but strings
        return typeof d[field] !== 'string' ? 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
          })
        })
      }
      rows.unshift(filteredFields)
      console.log(
        table(rows)
      )
    }
  }
}

module.exports = { displayTable }
