// SWAPI Links
function fetchGet(url) {
  return fetch(url)
    .then((response) => {
      if (response.ok) {
        return response.json(); // json() returns Promise!
      } else {
        return Promise.reject(new Error(response.statusText));
      }
    });
}

function swapiLinks(url) {
  let obj;
  return fetchGet(url)
    .then(response => {
      console.log(response);
      obj = response;
      const linkPromises = [];
      Object.values(obj).forEach(value => {
        if (typeof value == 'string' && value.includes('https://swapi.dev/api/')) {
          linkPromises.push(fetchGet(value));
        } else if (Array.isArray(value)) {
          value.forEach((el) => {
            if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
              linkPromises.push(fetchGet(el));
            }
          });
        }
      });
      return Promise.all(linkPromises);
    }).then(linkResponses => {
      Object.keys(obj).forEach(key => {
        if (typeof obj[key] == 'string' && obj[key].includes('https://swapi.dev/api/')) {
          obj[key] = linkResponses.shift();
        } else if (Array.isArray(obj[key])) {
          obj[key].forEach((el, i) => {
            if (typeof el == 'string' && el.includes('https://swapi.dev/api/')) {
              obj[key][i] = linkResponses.shift();
            }
          });
        }
      });
      return Promise.resolve(obj);
    })
    .catch((error) => {
      return Promise.reject(error);
    });
}

swapiLinks("https://swapi.dev/api/people/20/")
  .then(yodaWithLinks => {
    console.log(JSON.stringify(yodaWithLinks, null, 4));
  })
  .catch((error) => {
    console.log(error);
  });


// domEventPromise
{
  function domEventPromise(element, eventName) {
    function executor(resolve) {
      let fn = (event) => {
        resolve(event);
        element.removeEventListener(eventName, fn);
      };
      element.addEventListener(eventName, fn);

    }
    return new Promise(executor)
  }


  domEventPromise(document.getElementById('click'), 'click').then(e => console.log('event click happens', e))
}