// -----------------------------------------------------------------
// CONFIG
// -----------------------------------------------------------------

const maxStatLength = 15
const statNameSpacing = 5
const coloredWords = {
  red: ['lred'],
}

// -----------------------------------------------------------------

const fs = require('fs')

const dir = process.argv[2]
if (!dir) {
  console.log('No params')
  process.exit()
}

function getDayIndex(offset) {
  if (!offset) {
    offset = 0
  }

  let date = new Date()
  if (offset) {
    date.setDate(date.getDate() + offset)
  }
  return (
    date.getFullYear() +
    '/' +
    ('0' + (date.getMonth() + 1)).slice(-2) +
    '/' +
    ('0' + date.getDate()).slice(-2)
  )
}

function C(color) {
  if (color !== undefined) {
    color = color.toLowerCase()
  }

  if (color === 'redbg') {
    return '\x1b[41m'
  }
  if (color === 'bluebg') {
    return '\x1b[44m'
  }
  if (color === 'green') {
    return '\x1b[32m'
  }
  if (color === 'red') {
    return '\x1b[31m'
  }
  if (color === 'yellow') {
    return '\x1b[33m'
  }
  if (color === 'blue') {
    return '\x1b[34m'
  }
  if (color === 'magenta') {
    return '\x1b[35m'
  }
  if (color === 'cyan') {
    return '\x1b[36m'
  }
  return '\x1b[0m'
}

function readJSON(name) {
  return JSON.parse(fs.readFileSync(name, 'utf8'))
}

function tail(text, number) {
  let splitedText = text.split('\n')
  return splitedText.slice(Math.max(splitedText.length - number, 1)).join('\n')
}

function head(text, number) {
  return text
    .split('\n')
    .slice(0, number)
    .join('\n')
}

function readFile(name) {
  return fs.readFileSync(name, 'utf8')
}

function getLetterNTimes(letter, number) {
  let res = ''
  while (res.length < number) {
    res += letter
  }
  return res
}

function pCols() {
  // console.log(arguments)
  let maxLength = 0
  Object.keys(arguments).forEach((key) => {
    if (arguments[key].length > maxLength) {
      maxLength = arguments[key].length
    }
  })
  for (let i = 0; i < maxLength; i++) {
    let row = []
    Object.keys(arguments)
      .reverse()
      .forEach((key) => {
        const val = arguments[key]
        if (!val[i]) {
          return
        }

        const keyName = val[i].name || ''

        let slicedName = keyName.slice(0, maxStatLength)
        let toColor = Object.keys(coloredWords).reduce((acc, key) => {
          const colorArray = coloredWords[key]

          const includes = colorArray.some((colorableIdName) => {
            return keyName.includes(colorableIdName)
          })

          if (includes) {
            return key
          }

          return acc
        }, '')

        while (slicedName.length < maxStatLength) {
          slicedName = ' ' + slicedName
        }

        let ammount = val[i].val ? val[i].val.toString() : 0
        while (ammount.length < 4) {
          ammount = ammount + ' '
        }

        if (toColor) {
          row.push(C(toColor) + slicedName + ': ' + ammount + C())
        } else {
          row.push(slicedName + ' ' + ammount)
        }
      })
    console.log(row.join(getLetterNTimes(' ', statNameSpacing)))
  }
}

// ------------------------------------------------------------------------------
const dailyStats = readJSON(`${dir}stats/vstats`)
function preProcessDailyStats(obj) {
  return Object.keys(obj).map((key) => {
    return { name: key, val: obj[key] }
  })
}

pCols(
  preProcessDailyStats(dailyStats[getDayIndex()]),
  preProcessDailyStats(dailyStats[getDayIndex(-1)]),
  preProcessDailyStats(dailyStats[getDayIndex(-2)])
)

// ------------------------------------------------------------------------------
const userIdTestSolving = readJSON(`${dir}stats/idvstats`)
function preProcessUIdTestSolving(obj) {
  if (!obj) {
    return [{ val: 0 }]
  }
  return [{ val: Object.keys(obj).length }]
}

pCols(
  preProcessUIdTestSolving(userIdTestSolving[getDayIndex()]),
  preProcessUIdTestSolving(userIdTestSolving[getDayIndex(-1)]),
  preProcessUIdTestSolving(userIdTestSolving[getDayIndex(-2)])
)

// ------------------------------------------------------------------------------
const clientIdTestSolving = readJSON(`${dir}stats/uvstats`)

pCols(
  preProcessUIdTestSolving(clientIdTestSolving[getDayIndex()]),
  preProcessUIdTestSolving(clientIdTestSolving[getDayIndex(-1)]),
  preProcessUIdTestSolving(clientIdTestSolving[getDayIndex(-2)])
)

// ------------------------------------------------------------------------------
const dailyDataCount = readFile(`${dir}stats/dailyDataCount`)

printLastDataCount([
  JSON.parse(head(tail(dailyDataCount, 1), 1)),
  JSON.parse(head(tail(dailyDataCount, 2), 1)),
  JSON.parse(head(tail(dailyDataCount, 3), 1)),
])

function printLastDataCount(data) {
  const res = [[], [], []]
  data.forEach((dataCount, i) => {
    res[i].push({ val: dataCount.userCount })
    res[i].push({ val: dataCount.subjectCount })
    res[i].push({ val: dataCount.questionCount })
  })

  pCols(...res)
}