package com.zaojiao.app.core.auth.ui

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.zaojiao.app.core.auth.data.AuthRepository
import com.zaojiao.app.core.auth.model.TokenModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.runBlocking
import javax.inject.Inject
import kotlin.concurrent.thread

@AndroidEntryPoint
class TokenActivity : AppCompatActivity() {
    companion object {
        const val KEY_ACCESS = "access_token"
        const val KEY_REFRESH = "refresh_token"

        fun start(context: Context, accessToken: String?, refreshToken: String?) {
            val intent = Intent(context, TokenActivity::class.java)
            intent.data =
                Uri.parse("token://www.luojigou.vip/app?access_token=$accessToken&&refreshToken=$refreshToken")
            context.startActivity(intent)
        }
    }

    @Inject
    public lateinit var authRepository: AuthRepository

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

    override fun onNewIntent(newIntent: Intent?) {
        super.onNewIntent(intent)
        parseIntent(newIntent)
    }

    private fun parseIntent(parsedIntent: Intent?) {
        thread {
            var accessToken: String? = null
            var refreshToken: String? = null

            parsedIntent?.data?.apply {
                accessToken = this.getQueryParameter(KEY_ACCESS)
                refreshToken = this.getQueryParameter(KEY_REFRESH)
            }

            if (accessToken == null || refreshToken == null) {
                runBlocking {
                    authRepository.clearToken()
                }
            } else {
                runBlocking {
                    authRepository.updateToken(
                        TokenModel(
                            accessToken = accessToken!!,
                            refreshToken = refreshToken!!,
                        )
                    )
                }
            }

            val intent = Intent()
            intent.setClassName(packageName, "com.zaojiao.app.MainActivity")
            intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
            startActivity(intent)
            finish()
        }
    }
}