package de.storchp.fdroidbuildstatus

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.core.view.updatePadding
import de.storchp.fdroidbuildstatus.databinding.ActivityShowErrorBinding
import de.storchp.fdroidbuildstatus.utils.addInsetsListener
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.nio.charset.StandardCharsets.UTF_8

const val EXTRA_ERROR_TEXT = "error"

class ShowErrorActivity : AppCompatActivity() {
    private lateinit var binding: ActivityShowErrorBinding
    public override fun onCreate(savedInstanceState: Bundle?) {
        enableEdgeToEdge()
        super.onCreate(savedInstanceState)
        binding = ActivityShowErrorBinding.inflate(layoutInflater)
        binding.topAppBar.addInsetsListener {
            updatePadding(left = it.left, right = it.right)
        }
        binding.errorPageContainer.addInsetsListener {
            updatePadding(left = it.left, right = it.right, bottom = it.bottom)
        }
        setContentView(binding.root)
        setSupportActionBar(binding.topAppBar)
        binding.textViewError.text =
            intent.getStringExtra(EXTRA_ERROR_TEXT)
        if (supportActionBar != null) {
            supportActionBar!!.title = createErrorTitle()
        }
    }

    private fun createErrorTitle(): String {
        return String.format(getString(R.string.error_crash_title), getString(R.string.app_name))
    }

    private fun reportBug() {
        val uriUrl: Uri = try {
            String.format(
                getString(R.string.report_issue_link),
                URLEncoder.encode(binding.textViewError.text.toString(), UTF_8.toString())
            ).toUri()
        } catch (_: UnsupportedEncodingException) {
            // can't happen as UTF-8 is always available
            return
        }
        startActivity(Intent(Intent.ACTION_VIEW, uriUrl))
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.show_error, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.error_share) {
            onClickedShare()
            return true
        } else if (item.itemId == R.id.error_report) {
            reportBug()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun onClickedShare() {
        startActivity(Intent(Intent.ACTION_SEND).apply {
            putExtra(Intent.EXTRA_SUBJECT, createErrorTitle())
            putExtra(Intent.EXTRA_TEXT, binding.textViewError.text)
            type = "text/plain"
        })
    }

}