package com.duolebo.blyrobot.util

import android.text.TextUtils
import java.io.File
import java.io.FileFilter
import java.net.Inet4Address
import java.net.InetAddress
import java.net.NetworkInterface
import java.util.*

object AppUtil {
    fun deleteFile(file: File?, fileFilter: FileFilter) {
        if (file == null) {
            return
        }
        if (!fileFilter.accept(file)) {
            return
        }
        if (file.isFile) {
            file.delete()
            return
        }
        val files = file.listFiles()
        if (files == null) {
            file.delete()
            return
        }
        for (childFile in files) {
            deleteFile(childFile, fileFilter)
        }
        file.delete()
    }

    fun getIPAddress(useIPv4: Boolean, interfaceName: String?): String {
        try {
            val interfaces = Collections.list(NetworkInterface.getNetworkInterfaces())
            for (intf in interfaces) {
                if (!TextUtils.isEmpty(interfaceName) && intf.name != interfaceName) {
                    continue
                }
                val addrs = Collections.list(intf.inetAddresses)
                for (addr in addrs) {
                    if (!addr.isLoopbackAddress) {
                        val sAddr = addr.hostAddress.toUpperCase()
                        //                        boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr);
                        val isIPv4 = addr is Inet4Address //Since API-23 InetAddressUtils was removed
                        if (useIPv4) {
                            if (isIPv4)
                                return sAddr
                        } else {
                            if (!isIPv4) {
                                val delim = sAddr.indexOf('%') // drop ip6 port suffix
                                return if (delim < 0) sAddr else sAddr.substring(0, delim)
                            }
                        }
                    }
                }
            }
        } catch (ex: Exception) {
        }
        // for now eat exceptions
        return ""
    }
}