package oppen.filters.ui

import android.annotation.SuppressLint
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.OpenableColumns

object FilenameHelper {

    @SuppressLint("DefaultLocale")
    fun getSuggestedFilename(context: Context, uri: Uri?, filter: String): String? {
        var sourceFilename: String? = null
        if (uri != null && uri.scheme == "content") {
            val cursor: Cursor? = context.contentResolver.query(uri, null, null, null, null)
            cursor.use {
                if (cursor != null && cursor.moveToFirst()) {
                    sourceFilename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME))
                }
            }
        }

        if(sourceFilename != null) {
            sourceFilename = sourceFilename?.replace(" ", "_")?.toLowerCase()
            sourceFilename = sourceFilename?.substring(0, sourceFilename!!.lastIndexOf("."))
        }else{
            sourceFilename = "processing_image"
        }

        val cleanedFilterName = filter.replace(" ", "_").toLowerCase()
        var suggestedFilename = "${sourceFilename}_${cleanedFilterName}"

        suggestedFilename += ".png"

        return suggestedFilename
    }
}