package com.github.mondei1.offpass

import android.R.attr.key
import android.annotation.SuppressLint
import android.app.ActionBar
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import dev.turingcomplete.kotlinonetimepassword.GoogleAuthenticator
import kotlinx.android.synthetic.main.activity_create.*
import kotlinx.android.synthetic.main.activity_view.*
import kotlinx.android.synthetic.main.activity_view.back
import kotlinx.android.synthetic.main.activity_view.email_input
import kotlinx.android.synthetic.main.activity_view.fa_input
import kotlinx.android.synthetic.main.activity_view.fa_label
import kotlinx.android.synthetic.main.activity_view.fa_progress
import kotlinx.android.synthetic.main.activity_view.password_hide
import kotlinx.android.synthetic.main.activity_view.password_input
import kotlinx.android.synthetic.main.activity_view.title_label
import kotlinx.android.synthetic.main.activity_view.url_input
import kotlinx.android.synthetic.main.activity_view.username_input
import kotlinx.coroutines.*


class ViewActivity : AppCompatActivity() {

    var fa_coroutine: Job? = null

    override fun onBackPressed() {
        val i = Intent(this, MainActivity::class.java)
        i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        startActivity(i)
    }

    override fun setContentView(view: View?) {
        // Prevent other apps from making screenshots or to record Offpass.
        window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
    }

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_view)

        val qrSchema: QRSchema = QRSchema(this)

        back.setOnClickListener {
            val i = Intent(this, MainActivity::class.java)
            i.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(i)
        }
        password_hide.setOnClickListener {
            if (password_input.transformationMethod == HideReturnsTransformationMethod.getInstance()) {
                password_input.transformationMethod = PasswordTransformationMethod.getInstance()
                password_input.text = "123456"
                password_hide.setImageResource(R.drawable.ic_visibility_on)
            } else {
                password_input.transformationMethod = HideReturnsTransformationMethod.getInstance()
                password_input.text = qrSchema.password
                password_hide.setImageResource(R.drawable.ic_visibility_off)

            }
        }

        qrSchema.decrypted_raw = intent.getStringExtra("decrypted_raw")!!
        qrSchema.parse(this)

        title_label.text = qrSchema.title
        username_input.setText(qrSchema.username, TextView.BufferType.EDITABLE)
        password_input.setText("123456", TextView.BufferType.EDITABLE)
        email_input.setText(qrSchema.email, TextView.BufferType.EDITABLE)
        url_input.setText(qrSchema.website_url, TextView.BufferType.EDITABLE)

        if (qrSchema.custom.containsKey("2fa")) {
            val fa_uri = Uri.parse(qrSchema.custom.get("2fa"))
            val fa_generator = GoogleAuthenticator(base32secret = fa_uri.getQueryParameter("secret").toString())
            fa_label.text = "${fa_uri.path?.replace("/", "")} (${fa_uri.getQueryParameter("issuer")})"
            fa_progress.visibility = View.VISIBLE

            fa_coroutine = GlobalScope.launch(Dispatchers.Main) {
                while (true) {
                    fa_input.setText(fa_generator.generate())

                    var seconds_remaining = CryptoOperations().getRemainingTOTPTime()
                    Log.i("2FA Generator", "Remaining: $seconds_remaining")

                    if (seconds_remaining == 0) seconds_remaining = 30

                    // Change color
                    if (seconds_remaining >= 15) {
                        fa_progress.progressTintList = ColorStateList.valueOf(Color.GREEN)
                    } else if (seconds_remaining < 15 && seconds_remaining >= 8) {
                        fa_progress.progressTintList = ColorStateList.valueOf(Color.YELLOW)
                    } else {
                        fa_progress.progressTintList = ColorStateList.valueOf(Color.RED)
                    }

                    fa_progress.progress = seconds_remaining
                    delay(1000)
                }
            }
        } else {
            fa_layout.visibility = View.GONE
        }
    }

    override fun onStop() {
        super.onStop()
        fa_coroutine?.cancel(CancellationException("Activity is stopping"))
    }
}