package com.ypsx.base.util

import android.os.Environment
import com.ypsx.base.base.appContext
import java.io.File

object PathUtils {

    fun getLogParent(): String {
        val directory = if (Environment.getExternalStorageState() == Environment.MEDIA_MOUNTED) {
            // 有SD卡则使用SD - PS:没SD卡但是有外部存储器，会使用外部存储器
            // SD\Android\data\包名\files\Log\logs.txt
            File("${appContext.getExternalFilesDir("Log")?.path.toString()}/")
        } else {
            // 没有SD卡或者外部存储器，使用内部存储器
            // \data\data\包名\files\Log\logs.txt
            File("${appContext.filesDir.path}/Log/")
        }
        return directory.absolutePath
    }

    fun getUpLoadUrl(date: String): List<File>? {
        val logParent = getLogParent()
        logParent.dXLog()
        var file = File(logParent)
        if (file.exists()) {
            val files: Array<File> = file.listFiles() ?: return null
            return getFileUrl(files, date)
        }
        return null
    }

    private fun getFileUrl(files: Array<File>, date: String): List<File> {
        var filePath= arrayListOf<File>()
        for (file in files) {

            if (file.name.isNotEmpty() && file.name.contains(date)) {
                file.absolutePath.dXLog()
                filePath.add(file)
            }
        }
        return filePath
    }

    fun getZipUrl(date: String, tag: String): String {
        val logParent = getLogParent()
        val file = File(logParent)
        if (!file.exists()) {
            file.mkdirs()
        }
        val url = getUrl(file.absolutePath, date, tag)
        val file1 = File(url)
        if (file1.exists()) {
            file1.delete()
        }
        return url
    }

    private fun getUrl(dire: String, date: String, tag: String): String {

        return "$dire/$date$tag"
    }

}