import jira from '../jira'

const formatIssues = (issues) =>
  issues.map(issue => {
    const link = jira.linkToIssue(issue)
    return `* [${issue.key}](${link}) - ${issue.fields.summary}`
  }).join('\n')

const getErrorMessage = ({ error }, defaultStr) => {
  const { errorMessages = [] } = error
  return errorMessages.length ? errorMessages[0] : defaultStr
}

export const listMyIssues = (bot, message) =>
  listIssuesFor(bot, message, message.user)

export const listIssuesForUser = (bot, message) =>
  listIssuesFor(bot, message, message.match[message.match.length - 1])

export const listIssuesFor = async (bot, message, username) => {
  const users = await jira.findUsers(username)

  if (users.length === 0) {
    bot.reply(message, `Could not find any users matching "${username}"`)
  } else if (users.length !== 1) {
    bot.reply(message, `Expected 1 user, but found ${users.length}. Please be more specific.`)
  } else {
    const user = users[0]
    const { issues, total } = await jira.getIssues(user.key)

    let reply
    if (!total) {
      reply = `I found no open issues for ${user.displayName}`
    } else {
      const issuesStr = formatIssues(issues)
      reply = (
        `I found ${total} open issue(s) for ${user.displayName}. They are:\n${issuesStr}`
      )
    }
    bot.reply(message, reply)
  }
}

export const handleJoin = (bot, message) => {
  bot.reply(message, 'This trusty JIRA bot is here to help.')
}

export const createIssue = async (bot, message) => {
  const [projectKey, issueType, issueSummary] = message.match.slice(-3)

  let response
  try {
    response = await jira.createIssue(projectKey, issueType, issueSummary)
  } catch ({ error }) {
    console.log('Create issue failed', error)
    bot.reply(message, "I'm sorry, I was unable to create the issue")
    return
  }

  bot.reply(message, `[${response.key}](${jira.linkToIssue(response)}) created!`)
}

export const getIssueStatus = async (bot, message) => {
  const issueKey = message.match[message.match.length - 1]
  let response
  try {
    response = await jira.getIssue(issueKey)
  } catch (error) {
    const errorStr = getErrorMessage(error, 'I had trouble getting the issue details')
    bot.reply(message, `I could not get the status for "${issueKey}". ${errorStr}`)
    return
  }
  const { key, fields: { summary, status: { name } } } = response
  bot.reply(message, `[${key} - "${summary}"](${jira.linkToIssue(response)}) has status ${name}`)
}

export const commentOnIssue = async (bot, message) => {
  const [issueKey, body] = message.match.slice(-2)
  let response
  try {
    response = await jira.commentOnIssue(issueKey, body)
  } catch (error) {
    const errorStr = getErrorMessage(error, 'I had trouble posting the comment.')
    bot.reply(message, `I could not add your comment on "${issueKey}". ${errorStr}`)
    return
  }
  const { id } = response
  const link = `${jira.linkToIssue({ key: issueKey })}?focusedCommentId=${id}#comment-${id}`
  bot.reply(message, `Ok, I've added your comment to [${issueKey}](${link}).`)
}

export default {
  commentOnIssue,
  createIssue,
  getIssueStatus,
  handleJoin,
  listIssuesForUser,
  listMyIssues
}

@@ -2516,20 +2516,18 @@
  =%3E %7B%0A  
-cons
+le
 t %5Bissue
@@ -2563,16 +2563,354 @@
 ice(-2)%0A
+%0A  let displayName%0A  try %7B%0A    const user = await bot.botkit.api.people.get(message.original_message.personId)%0A    displayName = user.displayName%0A  %7D catch (error) %7B%0A    console.log(%60WARNING: Could not find display name for $%7Bmessage.user%7D%60)%0A  %7D%0A  if (displayName) %7B%0A    body = %60$%7BdisplayName%7D commented via Cisco Spark:%5Cn%5Cn$%7Bbody%7D%60%0A  %7D%0A%0A
   let re
@@ -3068,19 +3068,20 @@
 posting 
-the
+your
  comment

Add user's name in comment on ticket