package xyz.myachin.saveto.ui.supports

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.button.MaterialButton
import xyz.myachin.saveto.R
import xyz.myachin.saveto.logic.intent.ACTION_NEED_DOWNLOAD
import xyz.myachin.saveto.logic.intent.EXTRA_SAVE_URL_AS_TEXT
import xyz.myachin.saveto.settings.Settings

class NeedDownloaderActivity : AppCompatActivity(), View.OnClickListener {
    private lateinit var btOpen: MaterialButton
    private lateinit var btAlwaysAsText: MaterialButton
    private lateinit var btSaveAsText: MaterialButton

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_need_downloader)

        fillUI(intent)
    }

    private fun fillUI(intent: Intent?) {
        when (intent?.action) {
            ACTION_NEED_DOWNLOAD -> {
                findViewById<TextView>(R.id.tvExplain).text =
                    getString(R.string.need_downloader_message_2, getString(R.string.app_name))

                findViewById<MaterialButton>(R.id.btOpenMarket)?.also {
                    btOpen = it
                    it.setOnClickListener(this)
                }

                findViewById<MaterialButton>(R.id.btAlwaysAsText)?.also {
                    btAlwaysAsText = it
                    it.setOnClickListener(this)
                }

                findViewById<MaterialButton>(R.id.btSaveAsText)?.also {
                    btSaveAsText = it
                    it.setOnClickListener(this)
                }
            }
            else -> {
                finishAsCancel(false)
            }
        }
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            btOpen.id -> {
                Intent(Intent.ACTION_VIEW).also { market ->
                    market.action = Intent.ACTION_VIEW
                    market.data = Uri.parse("market://details?id=xyz.myachin.downloader")
                    setResult(RESULT_OK, market)
                }
                finish()
            }
            btAlwaysAsText.id -> {
                Settings.useDownloader = false
                finishAsCancel(true)
            }
            btSaveAsText.id -> finishAsCancel(true)
            else -> {
                finishAsCancel(false)
            }
        }
    }

    private fun finishAsCancel(needText: Boolean) {
        setResult(RESULT_CANCELED, Intent().putExtra(EXTRA_SAVE_URL_AS_TEXT, needText))
        finish()
    }
}