const express = require('express')
const cors = require('cors')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')
const slack = require('slack')

const port = process.env.PORT || 3000
const token = process.env.SLACK_TOKEN

const ohsTeam = {
  U1CTUKMT9: {}, // Zoé
  // U40MZ9EL9: {}, // Tugba
  U0BU8V7N0: {}, // Trev
  // U2NC0H2BS: {}, // Temi
  U0BUEB5BK: {}, // Paolo
  U0BU8SV4K: {}, // Michele
  // U1KU01R4K: {}, // Kristina
  U162CB0LC: {}, // James
  U0C160N8N: {}, // Christean
  U0BUPA30R: {}, // Chris
  U1CU5P4H0: {}, // Anna
}

const orbitTeam = {
  U2L4F0AF3: {}, // James
}

const team = ohsTeam

const slapp = Slapp({
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})


// fetch users and store as team members

const updateMembers = () => slack.users.list({ token }, (err, { members } = {}) => {
  if (err) throw new Error(err)

  console.log(`Fetched ${members.length} users`)
  console.log(members.map(({ id }) => id).join(', '))

  members.forEach((member) => {
    if (!team[member.id]) return
    team[member.id] = Object.assign(team[member.id], member)
  })
})

updateMembers()

setInterval(updateMembers, 10000)


// commands

slapp.command('/location', '(.*)', (msg, text, location) => {
  if (!team[msg.body.user_id]) 
    return msg.respond(`You are not added as a team member`)
  
  team[msg.body.user_id].location = location
  
  msg.respond(`Your location has been set as _${location}_`)
})


// public api

const app = slapp.attachToExpress(express())

app.use(cors())

app.get('/', (req, res) => {
  res.send('Hello world.')
})

app.get('/team', (req, res) => {
  res.send(team)
})


// start server

app.listen(port, (err) => {
  if (err) return console.error(err)
  console.log(`Listening on port ${port}`)
})

@@ -883,16 +883,53 @@
  = () =%3E
+ new Promise((resolve, reject) =%3E %7B%0A 
  slack.u
@@ -974,24 +974,26 @@
  = %7B%7D) =%3E %7B%0A
+  
   if (err) t
@@ -995,30 +995,23 @@
 rr) 
-throw new Error
+reject
 (err)%0A%0A
+  
   co
@@ -1055,16 +1055,18 @@
 users%60)%0A
+  
   consol
@@ -1112,16 +1112,18 @@
 ', '))%0A%0A
+  
   member
@@ -1142,24 +1142,26 @@
 ember) =%3E %7B%0A
+  
     if (!tea
@@ -1185,16 +1185,18 @@
 urn%0A    
+  
 team%5Bmem
@@ -1250,64 +1250,34 @@
 )%0A  
-%7D)%0A
+  
 %7D)%0A%0A
-updateMembers()%0A%0AsetInterval(updateMembers, 10000
+    resolve()%0A  %7D)%0A%7D
 )%0A%0A%0A
@@ -1738,21 +1738,176 @@
 %7B%0A  
-res.send(team
+updateMembers().then(%0A    () =%3E res.send(members), %0A    (err) =%3E %7B%0A      console.log('Error updating members')%0A      console.error(err)%0A      res.send(members)%0A    %7D%0A  
 )%0A%7D)

Update members on client request