var def = {
  company_name: { type: "class", update: ["textContent"] },
  phone_number: { type: "class", update: ["textContent"] },
  phone_number_link: { type: "class", update: ["href"] },
  company_email: { type: "class", update: ["textContent"] },
  company_email_link: { type: "class", update: ["href"] },
  website_name: { type: "class", update: ["textContent"] },
  website_link: { type: "class", update: ["href"] },
  website_link_text: { type: "class", update: ["textContent"] },
  copyright: { type: "class", update: ["textContent"] },
  country_name: { type: "class", update: ["textContent"] },
  address: { type: "class", update: ["textContent"] },
};

function checkCookie(name) {
  let matches = document.cookie.match(
    new RegExp(
      "(?:^|; )" +
        name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, "\\$1") +
        "=([^;]*)"
    )
  );
  return matches ? decodeURIComponent(matches[1]) : undefined;
}

function setLocation() {
  fetch(
    "https://api.ipgeolocation.io/ipgeo?apiKey=ac306a64495340599347c6d3f645dab1"
  )
    .then((response) => response.json())
    .then((data) => {
      if (data.city) {
        updateElementOnPageByClass(data.city, "current_state", "textContent");
        document.cookie = `userCity=${encodeURIComponent(data.city)}`;
      } else {
      }
    });
}

function updateElementOnPageByClass(variableValue, selector, attribute) {
  var elements = document.getElementsByClassName(selector);

  for (var i = 0; i < elements.length; i++) {
    var el = elements[i];
    el[attribute] = variableValue;
  }
}

window.addEventListener("DOMContentLoaded", (event) => {
  if (checkCookie("userCity")) {
    updateElementOnPageByClass(checkCookie("userCity"), "current_state", "textContent");
  } else {
    setLocation();
  }
  var date = new Date(Date.now() + (3600 * 1000 * 24))

  // "Sat, June 01, 2019"
  var untilDate = date.toLocaleString('en-US', {
    month: 'long', // "June"
    day: 'numeric', // "01"
  });

  updateElementOnPageByClass(untilDate, "until_date", "textContent");

  fetch("/resources/data.json")
    .then(function (data) {
      return data.json();
    })
    .then(function (json) {
      Object.keys(json).forEach(function (variableKey) {
        var variableValue = json[variableKey];

        if (variableValue) {
          var variableConfig = def[variableKey];
          if (variableConfig) {
            if (variableConfig.type === "class") {
              var update = variableConfig.update;
              update.forEach(function (attribute) {
                updateElementOnPageByClass(
                  variableValue,
                  variableKey,
                  attribute
                );
              });
            }
          }
        }
      });
    });
});

