Code viewer for World: kinda broken PRACTICAL (cl...
// Cloned by Conner Milstead on 4 Dec 2023 from World "WORKING PRACTICAL" by Conner Milstead 
// Please leave this clone trail here.
 
 
 //creating output
document.write ( `

<h1> Spotify API </h1>

<h2> *Learn How Popular Your Favorite Artist Is!* </h2>

From:
<a href='https://developer.spotify.com/documentation/web-api/tutorials/getting-started'>Spotify For Developers</a>.
<br> 

<pre>

</pre>

<h3> Enter Your Client Infomation </h3>

You will need both a Client ID and a Client Secret Code in order to use this. <br>
Go and create your own app in order to get this information   
<a href='https://developer.spotify.com/dashboard'>here</a>.
<br>
Enter the client information below and then learn more about your favorite Spotify artists!
<br>
<p>

<div id=enterID>
Enter Client ID: 
	<input    style='width:25vw;'    maxlength='2000'   NAME="clientID"    id="clientID"       VALUE='a08dcf1b58c54473b85e15a2a1c98288' >  
	<button onclick='setID();' class=ab-normbutton >Set Client ID</button>
</div>

<pre>

</pre>

<div id=enterSecret>
Enter Client Secret: 
	<input    style='width:25vw;'    maxlength='2000'   NAME="clientSecret"    id="clientSecret"       VALUE='106a086a299b45d5bd0bce52f1d08470' >  
	<button onclick='setSecret();'  class=ab-normbutton >Set Client Secret</button>
</div>

<pre>

</pre>

<div style="width:60vw; background-color:white;  border: 1px solid black; margin:20; padding: 20px;">
<h3> Enter a Spotify Artist Name </h3>
<INPUT style="width:50vw;" id=me value="Radiohead" >
<button onclick="sendchat();"     class=ab-normbutton > Enter </button> 
</div>

<div style="width:60vw; background-color:#ffffcc;  border: 1px solid black; margin:20; padding: 20px;">
<h3> Spotify Artists Info:  </h3>
<div id=them > </div>
</div>

<pre>

</pre>

` );





///////
function setID(){
    client_id = jQuery("input#clientID").val();
    console.log('client id: ' + client_id);
}

function setSecret(){
    client_secret = jQuery("input#clientSecret").val();
    console.log('client Secret: ' + client_secret);
}

var credentials = client_id + ':' + client_secret;
var encodedCredentials = btoa(credentials);

var accessToken = ' ';

var authOptions = {
  method: 'POST',
  headers: {
    'Authorization': 'Basic ' + encodedCredentials,
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: 'grant_type=client_credentials'
};

fetch('https://accounts.spotify.com/api/token', authOptions)
  .then(function(response) {
    if (response.ok) {
      return response.json();
    }
    throw new Error('Network response was not ok.');
  })
  .then(function(body) {
      
      accessToken = body.access_token;
      console.log('access token: ' + accessToken);
      
    console.log('Response Body:', body); // Output the entire response body JSON
    // Use the body object as needed
  })
  .catch(function(error) {
    console.log('There was a problem with the fetch operation: ', error.message);
  });
  
  
  
  
/////////
//Function to get artist ID by name
function getArtistID(artistName, accessToken) {
  var searchQuery = encodeURIComponent(artistName);
  var searchURL = `https://api.spotify.com/v1/search?q=${searchQuery}&type=artist`;

  var options = {
    method: 'GET',
    headers: {
      'Authorization': 'Bearer ' + accessToken
    }
  };

  return fetch(searchURL, options)
    .then(function(response) {
      if (response.ok) {
        return response.json();
      }
      throw new Error('Network response was not ok.');
    })
    .then(function(data) {
      console.log('Search Response:', data); // Log the response data for debugging

      var artists = data.artists.items;
      if (artists.length > 0) {
          console.log('artist id: ' + artists[0].id);
        return artists[0].id; // Return the first artist's ID
      } else {
        throw new Error('Artist not found.');
      }
    })
    .catch(function(error) {
      console.log('Error:', error.message);
      return null; // Return null if there's an error
    });
    
    
}
  
  

  
  ///////
  //sendChat function
  function sendchat() {
  var artistName = document.getElementById('me').value; // Get the artist name from the input field
  console.log('artist name: ' + artistName);

  getArtistID(artistName, accessToken)
    .then(function(artistID) {
      if (artistID) {
        // Fetch artist data using the obtained artist ID
        var artistOptions = {
          method: 'GET',
          headers: {
            'Authorization': 'Bearer ' + accessToken
          }
        };

        return fetch('https://api.spotify.com/v1/artists/' + artistID , artistOptions);
      } else {
        throw new Error('Artist ID not found.');
      }
    })
    .then(function(response) {
      if (response.ok) {
        return response.json();
      }
      throw new Error('Network response was not ok.');
    })
    .then(function(artistData) {
      // Display artist information in the HTML element with ID 'them'
      var artistInfoElement = document.getElementById('them');
      var genres = artistData.genres.join(', '); // Join genres into a string
      var popularityScore = artistData.popularity;

      artistInfoElement.innerHTML = `
        <h4>${artistData.name}</h4>
        <p>Popularity: ${artistData.popularity}</p>
        <p>Followers: ${artistData.followers.total}</p>
        <p>Genres: ${genres}</p>
        <!-- Add more artist information as needed -->
      `;
      
      // Check the popularity score and add a final line based on the score
      var popularityLine = '';
      if (popularityScore >= 95) {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is one of the most popular artists on the planet!';
      } else if (popularityScore >= 80) {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is extreme popular!';
      } else if (popularityScore >= 60) {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is quite popular.';
      } else if (popularityScore >= 40) {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is not very popular.';
      } else if (popularityScore >= 20) {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is very unknown.';
      } else {
        popularityLine = 'With a popularity score of ' + popularityScore + ', this artist is known by very few people!';
      }

      // Add the final line to the displayed artist information
      artistInfoElement.innerHTML += `<p>${popularityLine}</p>`;
      
    })
    .catch(function(error) {
      console.log('Error:', error.message);
    });
}