/*
* XMLHttpRequest data module
*/

var githubDataRequestModule = (function () {

  // private
  var request = new XMLHttpRequest();

  // show request object data
  function showData() {
    // for data export
    var exportValueArray = []

    // check status
    var status = request.status;

    // show data on ready state, show error state on 404 and clear nav list
    if (status === 404) {
      showDataDiv.classList.add("not-found");
      showDataDiv.innerHTML = "Username not found =(";
      navRepoList.innerHTML = "";

      return status;
    } else {
      if (request.readyState == 4) {
        // clear div and nav of previous content
        showDataDiv.innerHTML = "";
        navRepoList.innerHTML = "";

        // replace text in git-button, disbale til' user starts typing a new name
        gitButtonEl.innerHTML = "Switch user";
        gitButtonEl.classList.add('disabled');

        // save form value for pre-loading
        localStorage.setItem("GitHubUsername", inputEl.value);

        // enable export button on success
        exportButtonEl.classList.remove('disabled');

        // show nav
        navElement.classList.remove('nav-none');

        // printRepos(request);
        var nameArray = repositoryDataModule.grabRepoNames(request.response);
        for (var i = 0; i < nameArray.length; i++) {
          // render forms based on repos
          appendToDataElement(nameArray, i, showDataDiv);
          appendToNavElement(nameArray, i, navRepoList);

          // set event listeners on submit buttons
          formLocalStorageModule.setButtonElementListeners(nameArray, i);
          exportValueArray.push(formLocalStorageModule.setInitialFormValues(nameArray, i));
        }
      } else {
        console.log("RESPONSE NOT READY YET!");
      }
    }

    // for data export
    exportModule.setDataBlob(exportValueArray);
  }

  return {
    // send request object to obtain repo data, return Promise
    getData: function() {
      // https://developers.google.com/web/fundamentals/primers/promises/?hl=en
      return new Promise(function(resolve, reject) {
        // open and send
        request.open('get', 'https://api.github.com/users/' + inputEl.value + '/repos');

        // add listener to request object
        request.onload = function() {
            // This is called even on 404 etc
            // so check the status
            if (showData() === 404) {
              reject(Error(request.statusText));
            } else {
              // Resolve the promise with the response text
              resolve(request.response);
            }
        };

        // Handle network errors
        request.onerror = function() {
          reject(Error("Network Error"));
        };

        request.send();
        console.log("Request sent using \'" + inputEl.value + "\' username!");
      });
    },

    // check if the GitHubUsername key in local storage has been set (submitted),
    // if so, get data using that previously used key
    getDataCached: function() {
      if (localStorage["GitHubUsername"] !== undefined) {
        gitButtonEl.innerHTML = "Switch user";
        gitButtonEl.classList.add('disabled');

        inputEl.value = localStorage["GitHubUsername"];
        
        githubDataRequestModule.getData().then(function(response) {
          console.log('Success, cached data received!');
        }, function(error) {
          console.log('Failed on getting cached data!');
        });
      }
    }
  };
})();