import { COUNTRIES_PHONE_CODES, MAIN_PHONE_CODES_COUNTRIES } from '../../constans/countriesPhoneCodes';
import { Country } from '../../constans/country';

let maximumCodeLength = 0;
const invertedCountriesPhoneCodes: { [phoneCode: string]: Country } = {};
Object.entries(COUNTRIES_PHONE_CODES).forEach(([country, phoneCode]) => {
  invertedCountriesPhoneCodes[phoneCode] = country as Country;
  maximumCodeLength = Math.max(maximumCodeLength, phoneCode.length);
});
Object.entries(MAIN_PHONE_CODES_COUNTRIES).forEach(([phoneCode, country]) => {
  invertedCountriesPhoneCodes[phoneCode] = country as Country;
  maximumCodeLength = Math.max(maximumCodeLength, phoneCode.length);
});

/** Return {@link Country} for given phone */
export function countryForPhone(phone: string | undefined): Country | undefined {
  if (!phone) {
    return undefined;
  }

  // We will look for first maximum matched phone code.
  for (let i = maximumCodeLength; i > 1; --i) {
    const code = phone.slice(0, i);
    if (invertedCountriesPhoneCodes[code]) {
      return invertedCountriesPhoneCodes[code];
    }
  }

  return undefined;
}
