// Posted because Google will be the easiest place for me to find this later when I need it :-)

// --------------------------------------------------------------------------
// Adapted from https://stackoverflow.com/questions/53382465/how-can-i-determine-if-week-starts-on-monday-or-sunday-based-on-locale-in-pure-j
const weekStart = (region, language) => {
  const saturdayCountries = [ "AE", "AF", "BH", "DJ", "DZ", "EG", "IQ", "IR", "JO", "KW", "LY", "OM", "QA", "SD", "SY" ];
  const sundayCountries = [ "AG", "AR", "AS", "AU", "BD", "BR", "BS", "BT", "BW", "BZ", "CA", "CN", "CO", "DM", "DO", "AG",
    "ET", "GT", "GU", "HK", "HN", "ID", "IL", "IN", "JM", "JP", "KE", "KH", "KR", "LA", "MH", "MM", "MO", "MT", "MX",
    "MZ", "NI", "NP", "PA", "PE", "PH", "PK", "PR", "PT", "PY", "SA", "SG", "SV", "TH", "TT", "TW", "UM", "US", "VE",
    "VI", "WS", "YE", "ZA", "ZW" ];
  const saturdayLanguages = [ "ar", "arq", "arz", "fa" ];
  const sundayLanguages = [ "am", "as", "bn", "dz", "en", "gn", "gu", "he", "hi", "id", "ja", "jv", "km", "kn",
    "ko", "lo", "mh", "ml", "mr", "mt", "my", "ne", "om", "or", "pa", "ps", "sd", "sm", "sn", "su", "ta", "te", "th",
    "tn", "ur", "zh", "zu" ];

  if (region) {
    if (sundayCountries.includes(region)) {
      return "sun";
    } else {
      return saturdayCountries.includes(region) ? "sat" : "mon";
    }
  } else {
    if (sundayLanguages.includes(language)) {
      return "sun";
    } else {
      return saturdayLanguages.includes(language) ? "sat" : "mon";
    }
  }
}

// --------------------------------------------------------------------------
// console.log(weekStartLocale(navigator.language)); // "mon"
export const weekStartLocale = locale => {
  const parts = locale.match(/^([a-z]{2,3})(?:-([a-z]{3})(?=$|-))?(?:-([a-z]{4})(?=$|-))?(?:-([a-z]{2}|\d{3})(?=$|-))?/i);
  return weekStart(parts[4], parts[1]);
}