'use strict';

const prompt = require('prompt');
const rp = require('minimal-request-promise');
const qs = require('querystring');
const slackReply = require('./reply');
const slackParse = require('./parse');

module.exports = function slackSetup(api, bot, logError) {
  api.post('/slack/slash-command', request => {
    if (request.post.token === request.env.slackToken)
      return bot(slackParse(request.post))
        .then(slackReply)
        .catch(logError);
    else
      return slackReply('unmatched token' + ' ' + request.post.token + ' ' + request.env.slackToken);
  });

  api.get('/slack/landing', request => {
    return rp({
      method: 'POST',
      hostname: 'slack.com',
      port: 443,
      path: '/api/oauth.access',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: qs.encode({
        client_id: request.env.slackClientId,
        client_secret: request.env.slackClientSecret,
        code: request.queryString.code,
        redirect_uri: request.env.slackRedirectUrl
      })
    })
      .then(() => `<p>Thanks for installing the app.</p>`);

  }, {
    success: { contentType: 'text/html' }
  });
  
  api.addPostDeployStep('slackSlashCommand', (options, lambdaDetails, utils) => {
    return utils.Promise.resolve().then(() => {
      if (options['configure-slack-slash-command']) {
        console.log(`Your Slack redirect URL is ${lambdaDetails.apiUrl}/slack/landing`);

        utils.Promise.promisifyAll(prompt);

        prompt.start();
        return prompt.getAsync(['Slack Client ID', 'Slack Client Secret', 'Slack token'])
          .then(results => {
            const deployment = {
              restApiId: lambdaDetails.apiId,
              stageName: lambdaDetails.alias,
              variables: {
                slackClientId: results['Slack Client ID'],
                slackClientSecret: results['Slack Client Secret'],
                slackToken: results['Slack token'],
                slackRedirectUrl: `${lambdaDetails.apiUrl}/slack/landing`
              }
            };

            return utils.apiGatewayPromise.createDeploymentPromise(deployment);
          });
      }
    })
    .then(() => `${lambdaDetails.apiUrl}/slack/slash-command`);
  });
};

@@ -1077,43 +1077,210 @@
 %3E %60%3C
-p%3EThanks for installing the app.%3C/p
+!doctype html%3E%3Chtml%3E%3Chead%3E%3Cmeta http-equiv=%22refresh%22 content=%221;url=$%7Brequest.env.slackHomePageUrl%7D%22 /%3E%3C/head%3E%3Cbody%3E%3Cp%3EThanks for installing the app. You will be redirected in a second.%3C/p%3E%3C/body%3E%3C/html
 %3E%60);
@@ -1302,16 +1302,22 @@
 ccess: %7B
+%0A     
  content
@@ -1333,16 +1333,20 @@
 xt/html'
+%0A   
  %7D%0A  %7D);
@@ -1533,16 +1533,41 @@
 nd'%5D) %7B%0A
+        console.log('');%0A
         
@@ -1646,16 +1646,41 @@
 nding%60);
+%0A        console.log('');
 %0A%0A      
@@ -1829,16 +1829,33 @@
 k token'
+, 'Home page URL'
 %5D)%0A     
@@ -2204,24 +2204,84 @@
 ck token'%5D,%0A
+                slackHomePageUrl: results%5B'Home page URL'%5D,%0A
             
@@ -2374,16 +2374,59 @@
     %7D;%0A%0A
+            console.log(%60%0A            %60);%0A%0A
         

Add post deploy and prompt for slack