/* * * * * * * * * * * * *
 * Location form fields  *
 * * * * * * * * * * * * */

var db = new loki("csc.db");

const countriesJSON = "/static/data/countries.json";
const statesJSON = "/static/data/states.json";

/* Build database of countries and states and refresh related form options */
async function initLocations($cid = null) {
  let baseUrl = window.location.protocol + '//' + window.location.host;
  let headers = new Headers();
  // Allow fetch() to work on staging URLs protected by basic auth
  if (window.location.host.endsWith("donate-review.torproject.net")) {
    headers.set('Authorization', 'Basic ' + window.btoa("tor-www:"));
  }
  var countries = db.getCollection("countries");
  if (!countries) {
    let countries = db.addCollection("countries");
    let $country_select = $("[id^='id_country']");
    await fetch(baseUrl + countriesJSON, {
      headers: headers,
    })
      .then((response) => response.json())
      .then(async (data) => {
        $country_select.append(`
          <option disabled="true" selected="selected" value="">Select a country</option>
        `);
        await data.forEach((c) => {
          countries.insert(c);
          $country_select.append(`
            <option value="${c.name}" data-countryid="${c.id}" data-countrycode="${c.iso2}">${c.name}</option>
          `);
        });
      });
  }

  var states = db.getCollection("states");
  if (!states) {
    let states = db.addCollection("states");
    let $state_select = $("[id^='id_state']");
    await fetch(baseUrl + statesJSON, {
      headers: headers,
    })
      .then((response) => response.json())
      .then(async (data) => {
        if (data.length) {
          $state_select.html(`
            <option disabled="true" selected="selected" value="">Select a state</option>
          `);
        }
        await data.forEach((d) => {
          states.insert(d);
          if (d.country_id == $cid) {
            $state_select.append(`
              <option value="${d.name}">${d.name}</option>
            `);
          }
        });
      });
  }
}

/* Filter collection of states by country and refresh related form options */
async function filterStates($cid = null) {
  let statesColl = db.getCollection("states");
  let states = await statesColl.find({ country_id: parseInt($cid) });
  let $states = $("#id_state");
  let $states_label = $('label[for="id_state"]');
  $states.children("option").remove();
  if (states.length) {
    $states.html(
      "<option disabled='true' selected='selected' value=''>Select a state</option>"
    );
    await states.forEach((s) => {
      $states.append(`
        <option value="${s.name}">${s.name}</option>
      `);
    });
    $states.attr("required", true);
    $states_label.addClass("required");
  } else {
    $states.html(
      "<option disabled='true' selected='selected'>No state needed</option>"
    );
    $states.attr("required", false);
    $states_label.removeClass("required");
  }
  $states.removeClass('is-invalid');
}

export { initLocations, filterStates };
