package com.kdanmobile.reader.copyfile

import android.content.Context
import android.net.Uri
import android.support.v4.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 DocumentFile.fromSingleUri(context, uri)?.name ?: Uri.decode(uri.pathSegments?.last())
    }

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

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

    override fun getInputStream(): InputStream? {
        return context.contentResolver.openInputStream(uri)
    }
}