package com.doverfuelingsolutions.issp.data

import com.doverfuelingsolutions.issp.utils.sp.SPUtil
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.wayne.www.waynelib.fdc.message.DeviceClass
import java.lang.reflect.Type

class GlobalDataProvider<T>(private var value: T, private val sp: String = "") {

    companion object {
        private val gson = Gson()
    }

    private var cls = value!!::class.java
    private var convertType: Type? = null
    private val stringDefaultValue = gson.toJson(value, convertType ?: cls)

    private var isInit = false

    fun get(): T {
        if (!isInit && sp.isNotEmpty()) {
            val spValue = SPUtil.getString(sp, stringDefaultValue)
            value = gson.fromJson(spValue, convertType ?: cls)
        }
        return value
    }

    fun set(v: T) {
        value = v
        if (sp.isNotEmpty()) {
            SPUtil.putString(sp, gson.toJson(v, convertType ?: cls))
        }
    }

    fun converterToGSON(type: Type): GlobalDataProvider<T> {
        convertType = type
        return this
    }
}