{"size": 1774, "ext": "js", "max_stars_repo_path": "src/bot/commands/students.js", "max_stars_repo_name": "FowiFlowi/jedi-bot", "max_stars_repo_stars_event_min_datetime": "2019-04-25T15:05:06.000Z", "max_stars_repo_stars_event_max_datetime": "2019-11-27T21:45:24.000Z", "max_issues_repo_path": "src/bot/commands/students.js", "max_issues_repo_name": "FowiFlowi/jedi-bot", "max_issues_repo_issues_event_min_datetime": "2021-03-01T22:26:28.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-08T22:40:13.000Z", "max_forks_repo_path": "src/bot/commands/students.js", "max_forks_repo_name": "FowiFlowi/jedi-bot", "max_forks_repo_forks_event_min_datetime": "2020-01-23T20:16:27.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-23T20:16:27.000Z"}
{"max_stars_count": 2, "max_issues_count": 6, "max_forks_count": 1, "avg_line_length": 36.2040816327, "max_line_length": 104, "alphanum_fraction": 0.7249154453}
const { commands, roles } = require('config')

const userService = require('../service/user')
const directionService = require('../service/direction')
const extractUsername = require('../utils/extractUsername')
const escapeHtml = require('../utils/escapeHtml')
const getUsersCommand = require('../utils/getUsersCommand')
const CustomError = require('../../errors/CustomError')

async function getUserInfo(tgId) {
  const student = await userService.getOne(tgId)
  if (!student) {
    return 'No student with such telegram id'
  }

  const { directions } = student
  const dbDirections = await directionService.get({ ids: directions.map(item => item.id) })
  const regTime = student._id.getTimestamp()
  let answer = `${extractUsername(student)}\nRegister date: <b>${regTime.toString().slice(0, 21)}</b>\n`
    + '<b>Directions:</b>\n'
  dbDirections.forEach((direction, i) => answer += `${i + 1}. ${escapeHtml(direction.name)}\n`)
  return answer
}

async function getUserInfoByUsername(username) {
  const user = await userService.getByUsername(username, { role: roles.student })
  return getUserInfo(user.tgId)
}

async function getByDirectionOrUsername(param, listOptions) {
  const { skip, limit } = listOptions
  return userService.getByViewedDirection(param, {
    role: roles.student, skip, limit, format: true,
  })
    .catch(e => e instanceof CustomError ? undefined : Promise.reject(e))
    .then(byDirectionResult => byDirectionResult
      || getUserInfoByUsername(param))
    .catch(e => e instanceof CustomError ? e.message : Promise.reject(e))
}

const handlers = {
  getUsers: userService.getStudents,
  getUsersCount: userService.getStudentsCount,
  getUserInfo,
  getByDirectionOrUsername,
}

module.exports = getUsersCommand(commands.students, handlers)
