1+ package com.firebase.ui.auth.data.model
2+
3+ import android.os.Parcel
4+ import android.os.Parcelable
5+ import java.text.Collator
6+ import java.util.Locale
7+ import androidx.annotation.RestrictTo
8+
9+ @RestrictTo(RestrictTo .Scope .LIBRARY_GROUP )
10+ class CountryInfo (val locale : Locale , val countryCode : Int ) : Comparable<CountryInfo>, Parcelable {
11+
12+ // Use a collator initialized to the default locale.
13+ private val collator: Collator = Collator .getInstance(Locale .getDefault()).apply {
14+ strength = Collator .PRIMARY
15+ }
16+
17+ companion object {
18+ @JvmField
19+ val CREATOR : Parcelable .Creator <CountryInfo > = object : Parcelable .Creator <CountryInfo > {
20+ override fun createFromParcel (source : Parcel ): CountryInfo = CountryInfo (source)
21+ override fun newArray (size : Int ): Array <CountryInfo ?> = arrayOfNulls(size)
22+ }
23+
24+ fun localeToEmoji (locale : Locale ): String {
25+ val countryCode = locale.country
26+ // 0x41 is Letter A, 0x1F1E6 is Regional Indicator Symbol Letter A.
27+ // For example, for "US": 'U' => (0x55 - 0x41) + 0x1F1E6, 'S' => (0x53 - 0x41) + 0x1F1E6.
28+ val firstLetter = Character .codePointAt(countryCode, 0 ) - 0x41 + 0x1F1E6
29+ val secondLetter = Character .codePointAt(countryCode, 1 ) - 0x41 + 0x1F1E6
30+ return String (Character .toChars(firstLetter)) + String (Character .toChars(secondLetter))
31+ }
32+ }
33+
34+ // Secondary constructor to recreate from a Parcel.
35+ constructor (parcel: Parcel ) : this (
36+ parcel.readSerializable() as Locale ,
37+ parcel.readInt()
38+ )
39+
40+ override fun equals (other : Any? ): Boolean {
41+ if (this == = other) return true
42+ if (other !is CountryInfo ) return false
43+ return countryCode == other.countryCode && locale == other.locale
44+ }
45+
46+ override fun hashCode (): Int {
47+ var result = locale.hashCode()
48+ result = 31 * result + countryCode
49+ return result
50+ }
51+
52+ override fun toString (): String {
53+ return " ${localeToEmoji(locale)} ${locale.displayCountry} +$countryCode "
54+ }
55+
56+ fun toShortString (): String {
57+ return " ${localeToEmoji(locale)} +$countryCode "
58+ }
59+
60+ override fun compareTo (other : CountryInfo ): Int {
61+ val defaultLocale = Locale .getDefault()
62+ return collator.compare(
63+ locale.displayCountry.uppercase(defaultLocale),
64+ other.locale.displayCountry.uppercase(defaultLocale)
65+ )
66+ }
67+
68+ override fun describeContents (): Int = 0
69+
70+ override fun writeToParcel (dest : Parcel , flags : Int ) {
71+ dest.writeSerializable(locale)
72+ dest.writeInt(countryCode)
73+ }
74+ }
0 commit comments