package com.aletheia.app.util

import android.content.ClipData
import android.content.Context
import android.content.Intent
import androidx.core.content.FileProvider
import com.aletheia.app.R
import com.aletheia.app.model.Book
import com.aletheia.app.model.QBooksBook
import java.io.File
import java.io.FileNotFoundException
import java.util.Locale

object BookSharing {
    fun shareDownloadedBook(context: Context, book: Book) {
        val file = File(book.filePath)
        if (!file.isFile) {
            throw FileNotFoundException(context.getString(R.string.dialog_book_file_missing))
        }

        val uri = FileProvider.getUriForFile(
            context,
            "${context.packageName}.files",
            file,
            book.shareDisplayName()
        )
        val sendIntent = Intent(Intent.ACTION_SEND).apply {
            type = mimeType(book.format)
            putExtra(Intent.EXTRA_STREAM, uri)
            putExtra(Intent.EXTRA_SUBJECT, book.title)
            putExtra(Intent.EXTRA_TITLE, book.title)
            clipData = ClipData.newUri(context.contentResolver, book.title, uri)
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        val chooser = Intent.createChooser(sendIntent, context.getString(R.string.share_book_chooser_title)).apply {
            addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        }
        context.startActivity(chooser)
    }

    fun shareBookLink(context: Context, book: QBooksBook) {
        val url = book.shareUrl?.takeIf(String::isNotBlank)
            ?: book.downloadUrl.takeIf(String::isNotBlank)
            ?: error(context.getString(R.string.share_book_link_missing))
        val text = buildString {
            append(book.title)
            book.author.takeIf(String::isNotBlank)?.let {
                append('\n')
                append(it)
            }
            append('\n')
            append(url)
        }
        val sendIntent = Intent(Intent.ACTION_SEND).apply {
            type = "text/plain"
            putExtra(Intent.EXTRA_SUBJECT, book.title)
            putExtra(Intent.EXTRA_TEXT, text)
        }
        context.startActivity(Intent.createChooser(sendIntent, context.getString(R.string.share_book_chooser_title)))
    }

    private fun mimeType(format: String): String = when (format.lowercase(Locale.US)) {
        "epub" -> "application/epub+zip"
        "fb2" -> "application/x-fictionbook+xml"
        "pdf" -> "application/pdf"
        else -> "application/octet-stream"
    }

    private fun Book.shareDisplayName(): String {
        val extension = format.lowercase(Locale.US).ifBlank { "book" }
        val originalName = fileName
            .substringAfterLast('/')
            .substringAfterLast('\\')
            .trim()
            .ifBlank { "$title.$extension" }
        return originalName.replace(UNSAFE_FILE_NAME_CHARS, "_")
    }

    private val UNSAFE_FILE_NAME_CHARS = Regex("[\\u0000-\\u001F\\\\/:*?\"<>|]")
}
