taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

TalerUtils.kt (2212B)


      1 /*
      2  * This file is part of GNU Taler
      3  * (C) 2020 Taler Systems S.A.
      4  *
      5  * GNU Taler is free software; you can redistribute it and/or modify it under the
      6  * terms of the GNU General Public License as published by the Free Software
      7  * Foundation; either version 3, or (at your option) any later version.
      8  *
      9  * GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
     10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11  * A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     12  *
     13  * You should have received a copy of the GNU General Public License along with
     14  * GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15  */
     16 
     17 package net.taler.common
     18 
     19 import android.os.Build
     20 import androidx.annotation.RequiresApi
     21 import androidx.core.os.LocaleListCompat
     22 import java.util.Locale
     23 
     24 object TalerUtils {
     25 
     26     fun getLocalizedString(map: Map<String, String>?, default: String): String {
     27         // just return the default, if it is the only element
     28         if (map == null) return default
     29         if (Build.VERSION.SDK_INT < 26) return default
     30         // create a priority list of language ranges from system locales
     31         val locales = LocaleListCompat.getDefault()
     32         val priorityList = ArrayList<Locale.LanguageRange>(locales.size())
     33         for (i in 0 until locales.size()) locales[i]?.let { locale ->
     34             priorityList.add(Locale.LanguageRange(locale.toLanguageTag()))
     35         }
     36         // create a list of locales available in the given map
     37         val availableLocales = map.keys.mapNotNull {
     38             if (it == "_") return@mapNotNull null
     39             val list = it.split("_")
     40             when (list.size) {
     41                 1 -> Locale(list[0])
     42                 2 -> Locale(list[0], list[1])
     43                 3 -> Locale(list[0], list[1], list[2])
     44                 else -> null
     45             }
     46         }
     47         val match = Locale.lookup(priorityList, availableLocales)
     48         return match?.toString()?.let { map[it] } ?: default
     49     }
     50 
     51 }
     52 
     53 /**
     54  * Returns the current time in milliseconds epoch rounded to nearest seconds.
     55  */
     56 fun now(): Long {
     57     return ((System.currentTimeMillis() + 500) / 1000) * 1000
     58 }