package com.kdanmobile.reader.copyfile

import android.content.Context
import android.net.Uri
import androidx.documentfile.provider.DocumentFile
import java.io.File
import java.io.InputStream
import java.lang.Exception
import java.net.URI
import java.net.URLEncoder

class FileUriSource(private val context: Context, private val uri: Uri): CopyFileSource {

    override fun getFileName(): String? {
        return try {
            DocumentFile.fromSingleUri(context, uri)?.name ?: uri.lastPathSegment
        } catch (e: Exception) {
            null
        }
    }

    override fun getFilePath(): String? {
        return try {
            File(URI(URLEncoder.encode(uri.toString(), "UTF-8"))).absolutePath
        } catch (e: Exception) {
            null
        }
    }

    override fun getFileSize(): Long? {
        return try {
            val assetFileDescriptor = context.contentResolver.openAssetFileDescriptor(uri, "r")
            val fileSize = assetFileDescriptor?.length
            assetFileDescriptor?.close()
            fileSize
        } catch (e: Exception) {
            null
        }
    }

    override fun getInputStream(): InputStream? {
        return try {
            context.contentResolver.openInputStream(uri)
        } catch (e: Exception) {
            null
        }
    }
}