var SpotifyWebApi = require('spotify-web-api-node');
var fs = require('fs')
var userDetails = JSON.parse(fs.readFileSync('./data/userDetails.json', 'utf8'));
var path = require('path')

var credentials = {
    clientId: userDetails.clientId,
    clientSecret: userDetails.clientSecret,
    redirectUri: userDetails.redirectUri
  };
  
  var spotifyApi = new SpotifyWebApi(credentials);

  var token = JSON.parse(fs.readFileSync('./data/token.json', 'utf8'));
  
  // The code that's returned as a query parameter to the redirect URI
  var code = token.userToken;
  
  // Retrieve an access token and a refresh token
  spotifyApi.authorizationCodeGrant(code).then(
    function(data) {
      console.log('The token expires in ' + data.body['expires_in']);
      console.log('The access token is ' + data.body['access_token']);
      console.log('The refresh token is ' + data.body['refresh_token']);

    const accessData = {}
      accessData.access_token = data.body['access_token'];
      accessData.refresh_token = data.body['refresh_token'];

      fs.writeFileSync('./data/accessData.json', JSON.stringify(accessData))
  
      // Set the access token on the API object to use it in later calls
      spotifyApi.setAccessToken(data.body['access_token']);
      spotifyApi.setRefreshToken(data.body['refresh_token']);
    },
    function(err) {
      console.log('Something went wrong!', err);
    }
  );