package xyz.myachin.saveto.ui.permission

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.provider.Settings
import android.view.View
import android.widget.Button
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.PermissionChecker
import xyz.myachin.saveto.R

class RequestPermissionActivity : AppCompatActivity(), View.OnClickListener {
    private val mRES = Manifest.permission.READ_EXTERNAL_STORAGE
    private val permissionCode = 20

    private lateinit var mBtRequestPermissionNow: Button
    private lateinit var mBtOpenSettings: Button
    private lateinit var mBtCancel: Button

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        if (checkPermission()) return

        setContentView(R.layout.activity_request_permission)

        mBtRequestPermissionNow = findViewById(R.id.btRequestNow)
        mBtOpenSettings = findViewById(R.id.btRequestManual)
        mBtCancel = findViewById(R.id.btNextTime)

        mBtRequestPermissionNow.setOnClickListener(this)
        mBtOpenSettings.setOnClickListener(this)
        mBtCancel.setOnClickListener(this)
    }

    private fun checkPermission(): Boolean {
        if (PackageManager.PERMISSION_GRANTED == checkSelfPermission(mRES)) {
            finishWithCode(RESULT_OK)
            return true
        }
        return false
    }

    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btRequestNow -> {
                requestPermissions(arrayOf(mRES), permissionCode)
            }
            R.id.btRequestManual -> {
                Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                    data = Uri.fromParts("package", applicationContext.packageName, null)
                    startActivity(this)
                }
            }
            R.id.btNextTime -> {
                finishWithCode(RESULT_CANCELED)
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (permissionCode == requestCode) {
            grantResults.forEach { permissionResult ->
                if (PermissionChecker.PERMISSION_GRANTED != permissionResult) {
                    return
                }
            }
            finishWithCode(RESULT_OK)
            return
        }
        Toast.makeText(applicationContext, R.string.unexpected_request_code, Toast.LENGTH_LONG)
            .show()
        finishWithCode(RESULT_CANCELED)
    }

    private fun finishWithCode(code: Int) {
        setResult(code)
        finish()
    }

    override fun onResume() {
        super.onResume()
        checkPermission()
    }
}