import { countryType, populateType, returnT, CountryFnType } from "../types"
import { populateStatesCities, PATH, PATH_LITE, countryDir } from "../utils"

export const Country: CountryFnType = countryHandler()
export const CountryLite: CountryFnType = countryHandler('lite')

function countryHandler(type?: 'lite'): CountryFnType {
    const path = type === 'lite' ? PATH_LITE : PATH
    const fn: CountryFnType = function (countryIso2?: countryType | populateType, populate?: populateType): returnT {
        if (!countryIso2 || typeof countryIso2 == 'object') {
            const countries: Array<{}> = []
            for (const code of countryDir) {
                const country = require(`${path}/countries/${code}/index.json`)
                populateStatesCities(country, countryIso2, type)
                countries.push(country)
            }
            return countries
        }
        try {
            const country: any = require(`${path}/countries/${countryIso2}/index.json`)
            populateStatesCities(country, populate, type)
            return country ?? null
        } catch (e) {
            return null
        }
    }
    return fn
}