package com.aiosman.riderpro.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import coil.ImageLoader
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.CachePolicy
import com.aiosman.riderpro.data.api.AuthInterceptor
import com.aiosman.riderpro.data.api.getUnsafeOkHttpClient
import java.io.File
import java.io.FileOutputStream
import java.util.Date
import java.util.Locale
import java.util.UUID
import java.util.concurrent.TimeUnit

object Utils {
    fun generateRandomString(length: Int): String {
        val allowedChars = ('A'..'Z') + ('a'..'z') + ('0'..'9')
        return (1..length)
            .map { allowedChars.random() }
            .joinToString("")
    }

    fun getImageLoader(context: Context): ImageLoader {
        val okHttpClient = getUnsafeOkHttpClient(authInterceptor = AuthInterceptor())
        return ImageLoader.Builder(context)
            .okHttpClient(okHttpClient)
            .memoryCachePolicy(CachePolicy.ENABLED)
            .diskCachePolicy(CachePolicy.ENABLED)
//            .memoryCache {
//                MemoryCache.Builder(context)
//                    .maxSizePercent(0.25) // 设置内存缓存大小为可用内存的 25%
//                    .build()
//            }
//            .diskCache {
//                DiskCache.Builder()
//                    .directory(context.cacheDir.resolve("image_cache"))
//                    .maxSizePercent(0.02) // 设置磁盘缓存大小为可用存储空间的 2%
//                    .build()
//            }
            .build()
    }

    fun getTimeAgo(date: Date): String {
        val now = Date()
        val diffInMillis = now.time - date.time

        val seconds = TimeUnit.MILLISECONDS.toSeconds(diffInMillis)
        val minutes = TimeUnit.MILLISECONDS.toMinutes(diffInMillis)
        val hours = TimeUnit.MILLISECONDS.toHours(diffInMillis)
        val days = TimeUnit.MILLISECONDS.toDays(diffInMillis)
        val years = days / 365

        return when {
            seconds < 60 -> "$seconds seconds ago"
            minutes < 60 -> "$minutes minutes ago"
            hours < 24 -> "$hours hours ago"
            days < 365 -> "$days days ago"
            else -> "$years years ago"
        }
    }

    fun getCurrentLanguage(): String {
        return Locale.getDefault().language
    }

    fun compressImage(context: Context, uri: Uri, maxSize: Int = 512, quality: Int = 85): File {
        val inputStream = context.contentResolver.openInputStream(uri)
        val originalBitmap = BitmapFactory.decodeStream(inputStream)
        val (width, height) = originalBitmap.width to originalBitmap.height

        val (newWidth, newHeight) = if (width > height) {
            maxSize to (height * maxSize / width)
        } else {
            (width * maxSize / height) to maxSize
        }

        val scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true)
        val uuidImageName = UUID.randomUUID().toString().let { "$it.jpg" }
        val compressedFile = File(context.cacheDir, uuidImageName)
        val outputStream = FileOutputStream(compressedFile)
        if (quality > 100) {
            throw IllegalArgumentException("Quality must be less than 100")
        }
        if (quality < 0) {
            throw IllegalArgumentException("Quality must be greater than 0")
        }
        scaledBitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        outputStream.flush()
        outputStream.close()

        return compressedFile
    }
}