package com.hanwha.morakmorak.ui.splash

import android.content.Context
import android.view.View
import com.hanwha.morakmorak.core.BaseViewModel
import com.hanwha.morakmorak.data.local.preferences.UserPreferences
import com.hanwha.morakmorak.data.remote.api.UserAPI
import com.hanwha.morakmorak.extensions.with
import com.hanwha.morakmorak.util.CommonUtils
import io.jsonwebtoken.Jwts
import timber.log.Timber

/**
 * Created by aaron on 2019-09-20
 */
class SplashViewModel(private val api: UserAPI, private val prefs: UserPreferences) : BaseViewModel() {

    lateinit var onSplashClick: (View) -> Unit
    lateinit var loginComplete: (Boolean) -> Unit

    fun login(context: Context) {
        val params = mutableMapOf("deviceUID" to CommonUtils.getUuid(context))

        addToDisposable(api.login(params).with()
                .doOnSubscribe { isProgressVisible.value = true }
                .doOnSuccess { isProgressVisible.value = false }
                .doOnError { isProgressVisible.value = false }
                .subscribe({
                    Timber.i("onResponse!!!")
                    setUserInfo(it)
                    loginComplete(true)
                }, {
                    // handle errors
                    Timber.i("onError!!!")
                    Timber.i(it)
                    loginComplete(false)
                }))
    }

    private fun setUserInfo(token: String?) {
        token?.let {
            Timber.i("User token - $it")
            prefs.userToken = it
            prefs.userId = parseUserId(it)
        }
    }

    private fun parseUserId(token: String?) =
            Jwts.parser()
                    .parseClaimsJwt(token?.substringBeforeLast(".").plus("."))
                    .body["userId"] as Int
}