'use strict'

// BASE SETUP
// =============================================================================
import express, { Router } from 'express'
import { createServer } from 'http'
import bodyParser from 'body-parser'
import uuid from 'node-uuid'
import fetch from 'node-fetch'
import slackClient, { WebClient } from '@slack/client'

const app = new express()
const port = process.env.PORT || 8080
const router = new Router()

// API.AI Config
// Add security for prod-env
const postURL = `https://api.api.ai/v1/query?v=20150910`
const accessToken = `fa0f2e28ce9043b1a781e91c2fdaa850`
let sessionId = uuid.v1()
let message = null
let aiResponse = null

// Slackbot config
const slackToken = `xoxb-121768532438-soYL4i93cDnfs8j1QYqs3jNC`
const slackWebClient = new WebClient(slackToken)

// CREATE & RUN SEVER
// =============================================================================
createServer(app)
app.listen(port)
console.log('The Butler Server is running on port: ' + port)

// BODY PARSER SETUP
// =============================================================================
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())

// SERVER ROUTES
// =============================================================================

// Middleware
app.use(function (request, response, next) {
    // console.log('Connection detected!')
    next()
})

// Browser paths
app.use('/', express.static('client'))

// Api Routes
router.get('/', function (request, response) {
    response.send('<h1>Welcome to The Ape Butler API!</h1>')
})

router.post(`/`, (request, response) => {
    message = request.body.message
    console.log(`From Web Client: ` + message + `\n`)

    // API.AI REQUEST
    // =============================================================================
    // aiRequest(message, app)

    let requestBody = {
        "query": [
            message
        ],
        "timezone": "Europe/Stockholm",
        "lang": "en",
        "sessionId": sessionId
    }

    fetch(postURL, {
        method: 'POST',
        body: JSON.stringify(requestBody),
        headers: {
            'Content-Type': 'application/json; charset=utf-8',
            'Authorization': 'Bearer ' + accessToken
        },
    }).then(function (res) {
        return res.json();
    }).then(function (json) {
        // aiResponse = json.result.parameters
        // console.log(`Response from API.ai: \n` + JSON.stringify(aiResponse))

        // let givenname = json.result.parameters.givenname
        // let lastname = json.result.parameters.lastname
        // console.log(givenname + ` ` + lastname)

        let aiResponse = {
            'givenname': json.result.parameters.givenname,
            'lastname': json.result.parameters.lastname,
            'fullname': json.result.parameters.givenname + ' ' + json.result.parameters.lastname
        }

        console.log(`API.ai: ` + aiResponse.fullname + `\n`)

        // slackWebClient.chat.postMessage(`@anders`, `Hello from The Butler Bot`, (err, res) => {
        //     if (err) {
        //         console.log('Error: ' + err)
        //     } else {
        //         console.log('Message sent: ' + res)
        //     }
        // })

        slackWebClient.users.list(function (err, users) {
            if (err) {
                console.log('Error:', err + `\n`);
            } else {
                console.log('Slack API:')
                console.log(`Matching: ` + aiResponse.fullname + `\n`);
                for (var i in users.members) {
                    if (users.members[i].real_name === aiResponse.fullname) {
                        let slackName = users.members[i].real_name
                        console.log(`Found match: \n` + slackName + ` ID: ` + users.members[i].id)
                        // console.log(`Found match! \n`)
                        response.json(slackName)




                        return
                    }
                }
            }
        });

        // response.json(slackName)
    })

})
app.use('/api', router)


@@ -3650,20 +3650,20 @@
 et slack
-Name
+User
  = users
@@ -3673,26 +3673,16 @@
 mbers%5Bi%5D
-.real_name
 %0A       
@@ -3739,16 +3739,27 @@
 lack
-N
+User.real_n
 ame + %60
+,
  ID:
@@ -3767,86 +3767,485 @@
 %60 + 
-users.members%5Bi%5D.id)%0A                        // console.log(%60Found match! %5Cn%60)
+slackUser.id)%0A                        %0A                        slackWebClient.chat.postMessage(slackUser.id, %60Hello %60 + slackUser.real_name + %60! You have a guest!%60, (error, response) =%3E %7B%0A                            if (error) %7B%0A                                console.error(%60Error: %60 + error)%0A                            %7D else %7B%0A                                console.log(%60Message sent: %60 + JSON.stringify(response))%0A                            %7D%0A                        %7D)%0A
 %0A   
@@ -4288,17 +4288,13 @@
 lack
-Name)%0A%0A%0A%0A
+User)
 %0A   

Send message to slack user