// Foursquare API Info
const clientId ='ZUQT4GLKGABQVEYH53PB0NO5VJXP4DXCWMGDNTZZHO3LNWT1';
const clientSecret ='HQEFIZ113VS35OOZVFL0SQYDKBDWP4LAPJPKJOJWWPJUPVPP'
const url = 'https://api.foursquare.com/v2/venues/explore?near=';

// OpenWeather Info
const openWeatherKey = 'f8f3fa023d23a1b9d80516b165c59df2';
const weatherUrl =  'https://api.openweathermap.org/data/2.5/weather';

// Page Elements
const $input = $('#city');
const $submit = $('#button');
const $destination = $('#destination');
const $container = $('.container');
const $result = $('.result');
const $venueDivs = [$("#venue1"), $("#venue2"), $("#venue3"), $("#venue4")];
const $weatherDiv = $("#weather1");
const weekDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
const $validate = $('#validate');




const getVenues = async () => {
  const city = $input.val();
const urlToFetch = `${url}${city}&limit=10&client_id=${clientId}&client_secret=${clientSecret}&v=20210221`;
    try {
      const response = await fetch(urlToFetch);
      if( response.ok){
       const jsonResponse = await response.json();
       const venues = jsonResponse.response.groups[0].items.map(item => item.venue);
       console.log(venues);
       return venues
  }
  } catch (error) {
      console.log(error);
    }
  }




const getForecast = async () => {
  try {
    const urlToFetch = `${weatherUrl}?&q=${$input.val()}&APPID=${openWeatherKey}`;
    const response = await fetch(urlToFetch)
    if(response.ok){
    const jsonResponse = await response.json();
    console.log(jsonResponse);
    return jsonResponse;
    }

  } catch (error) {
    console.log(error);
  }

}


// Render functions
const renderVenues = (venues) => {
  $venueDivs.forEach(($venue, index) => {
    const venue = venues[index]
    const venueIcon = venue.categories[0].icon;
    const venueImgSrc = `${venueIcon.prefix}bg_64${venueIcon.suffix}`;
    let venueContent = createVenueHTML(venue.name, venue.location, venueImgSrc);
    $venue.append(venueContent);
  });
  $destination.append(`<h2>${venues[0].location.city}</h2>`);
}

const renderForecast = (day) => {
	let weatherContent = `${createWeatherHTML(day)}`;
  $weatherDiv.append(weatherContent);
}

const city = document.getElementById('city')

const executeSearch = (event) => {
  event.preventDefault()
  if(city.value.length <= 0){
    city.classList.add("is-invalid")
  }else{
    city.classList.remove("is-invalid")
    $venueDivs.forEach(venue => venue.empty());
    $weatherDiv.empty();
    $destination.empty();
    $result.css("display", "none")
    $container.css("display", "block");
    getVenues().then(venues => renderVenues(venues))
    getForecast().then(forcast =>renderForecast(forcast))

    return false;
  }
 
  }

$submit.click(executeSearch)