import org.mozilla.rocket.GenerateLocaleTask
// -------------------------------------------------------------------------------------------------
// L10N: Generate list of locales
// Focus provides its own (Android independent) locale switcher. That switcher requires a list
// of locale codes. We generate that list here to avoid having to manually maintain a list of locales:
// -------------------------------------------------------------------------------------------------

project.ext.removeR = {
    if (it.length() > 3 && it.contains("-r")) {
        // Android resource dirs add an "r" prefix to the region - we need to strip that for java usage
        // Add 1 to have the index of the r, without the dash
        def regionPrefixPosition = it.indexOf("-r") + 1

        return it.substring(0, regionPrefixPosition) + it.substring(regionPrefixPosition + 1)
    } else {
        return it
    }
}

def getEnabledLocales() {
    def resDir = file('src/main/res')

    def potentialLanguageDirs = resDir.listFiles(new FilenameFilter() {
        @Override
        boolean accept(File dir, String name) {
            return name.startsWith("values-");
        }
    })

    def langs = potentialLanguageDirs.findAll {
        // Only select locales where strings.xml exists
        // Some locales might only contain e.g. sumo URLS in urls.xml, and should be skipped (see es vs es-ES/es-MX/etc)
        return file(new File(it, "strings.xml")).exists()
    }.collect {
        // And reduce down to actual values-* names
        return it.name
    }.collect {
        return it.substring("values-".length())
    }.collect(removeR)
    .collect {
        return '"' + it + '"'
    }

    // en-US is the default language (in "values") and therefore needs to be added separately
    langs << "\"en-US\""
    // Remove zh-CN since we have it in our source code but we currently don't want it packaged.
    langs.remove("\"zh-CN\"")

    return langs
}

task generatePreviewLocaleList(type: GenerateLocaleTask) {
    directory = getGenerateDirectory("preview")
    locales = getEnabledLocales()
}

def addQuotes = { i -> '"' + i + '"'}

task generateFocusLocaleList(type: GenerateLocaleTask) {
    directory = getGenerateDirectory("focus")
    def keptLocaleList = Localization.KEPT_LOCALE.toList()
    keptLocaleList.add("en-US")
    locales = keptLocaleList.stream().map(addQuotes).map(removeR).toArray()
}

clean.doLast {
    file(getGenerateDirectory("preview")).deleteDir()
    file(getGenerateDirectory("focus")).deleteDir()
}

static def getGenerateDirectory(String flavor) {
    return 'src/'+ flavor + '/java/org/mozilla/focus/generated'
}