package com.grkj.iscs.model

import android.content.Context
import android.content.SharedPreferences
import java.util.concurrent.TimeUnit

class Token(
    val token: String,
    private val expiresAt: Long
) {


    fun saveToSp(context:Context): Boolean {
        val now = System.currentTimeMillis() / 1000
        return tokenSp(context).edit()
            .putString("token", token)
            .putLong("expiresAt", now + 60 * 60 * 2)
            .commit()
    }

    fun isValid(): Boolean {
        return expiresAt < 0 || expiresAt > System.currentTimeMillis() / 1000
    }

    override fun toString(): String {
        return "Token(token='$token', expiresAt=$expiresAt)"
    }

    companion object {

        fun fromSp(context:Context): Token? {
            val sp = tokenSp(context)
            val token = sp.getString("token", null)
            if (token == null) {
                return null
            }
            val expiresAt = sp.getLong("expiresAt", 0)
            val now = System.currentTimeMillis() / 1000
            if (expiresAt < now) {
                return null
            }
            return Token(token, expiresAt)
        }

        fun clear(context: Context) : Boolean {
            return tokenSp(context).edit()
                .putString("token", null)
                .putLong("expiresAt", 0)
                .commit()
        }

        private fun tokenSp(context: Context): SharedPreferences {
            return context.getSharedPreferences("token", Context.MODE_PRIVATE)
        }

        fun refresh(context: Context) {
            val now = System.currentTimeMillis() / 1000
            val sp = tokenSp(context)
            sp.edit().putLong("expiresAt", now + 60 * 60 * 2).apply()
        }
    }
}