text: const express = require('express'); // Express web server framework
  const router = express.Router();
  const request = require('request'); // "Request" library
  const cors = require('cors');
  const querystring = require('querystring');
  const cookieParser = require('cookie-parser');
  const config = require('../config.json');
  
  const client_id = config.CLIENT_ID;
  const client_secret = config.CLIENT_SECRET;
  const redirect_uri = config.REDIRECT_URI;
  const scope = config.SCOPE;
  
  router.use(cors())
  
  /* GET home page. */
  router.get('/', function (req, res, next) {
      res.render('index', { title: 'Example of the Authorization Code flow with Spotify' });
  });
  
  /**
   * Generates a random string containing numbers and letters
   * @param  {number} length The length of the string
   * @return {string} The generated string
   */
  const generateRandomString = function (length) {
      let text = '';
      let possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  
      for (let i = 0; i < length; i++) {
          text += possible.charAt(Math.floor(Math.random() * possible.length));
      }
      return text;
  };
  
  const stateKey = 'spotify_auth_state';
  
  // your application requests authorization
  router.get('/login', function (req, res) {
      let state = generateRandomString(16);
      res.cookie(stateKey, state);
      console.log(redirect_uri);
  
      res.redirect('https://accounts.spotify.com/authorize?' +
          querystring.stringify({
              response_type: 'code',
              client_id: client_id,
              scope: scope,
              redirect_uri: redirect_uri,
              state: state
          }));
  });
  
  // your application requests refresh and access tokens
  // after checking the state parameter
  router.get('/callback', function (req, res) {
      const code = req.query.code || null;
      const state = req.query.state || null;
      const storedState = req.cookies ? req.cookies[stateKey] : null;
  
      if (state === null || state !== storedState) {
          res.redirect('/#' +
              querystring.stringify({
                  error: 'state_mismatch'
              }));
      } else {
          res.clearCookie(stateKey);
          const authOptions = {
              url: 'https://accounts.spotify.com/api/token',
              form: {
                  code: code,
                  redirect_uri: redirect_uri,
                  grant_type: 'authorization_code'
              },
              headers: {
                  'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64'))
              },
              json: true
          };
  
          request.post(authOptions, function (error, response, body) {
              if (!error && response.statusCode === 200) {
  
                  const access_token = body.access_token,
                      refresh_token = body.refresh_token;
  
                  const options = {
                      url: 'https://api.spotify.com/v1/me',
                      headers: { 'Authorization': 'Bearer ' + access_token },
                      json: true
                  };
  
                  // use the access token to access the Spotify Web API
                  request.get(options, function (error, response, body) {
                      console.log(body);
                  });
  
                  // we can also pass the token to the browser to make requests from there
                  res.redirect('/#' +
                      querystring.stringify({
                          access_token: access_token,
                          refresh_token: refresh_token
                      }));
              } else {
                  res.redirect('/#' +
                      querystring.stringify({
                          error: 'invalid_token'
                      }));
              }
          });
      }
  });
  
  // requesting access token from refresh token
  router.get('/refresh_token', function (req, res) {
      const refresh_token = req.query.refresh_token;
      const authOptions = {
          url: 'https://accounts.spotify.com/api/token',
          headers: { 'Authorization': 'Basic ' + (new Buffer(client_id + ':' + client_secret).toString('base64')) },
          form: {
              grant_type: 'refresh_token',
              refresh_token: refresh_token
          },
          json: true
      };
  
      request.post(authOptions, function (error, response, body) {
          if (!error && response.statusCode === 200) {
              const access_token = body.access_token;
              res.send({
                  'access_token': access_token
              });
          }
      });
  });
  
  module.exports = router;
  