package com.gh.vspace.db

import androidx.room.TypeConverter
import com.gh.gamecenter.common.utils.toObject
import com.gh.gamecenter.common.utils.tryWithDefaultCatch
import com.gh.gamecenter.core.utils.GsonUtils
import com.lightgame.download.DownloadEntity
import com.lightgame.download.DownloadStatus
import org.json.JSONObject

class VGameConverter {

    @TypeConverter
    fun convertDownload2String(any: DownloadEntity): String {
        return GsonUtils.toJson(any)
    }

    @TypeConverter
    fun convertString2DownloadEntity(string: String): DownloadEntity {
        val downloadEntity = DownloadEntity()

        val rawJsonObject = JSONObject(string)

        val keys = rawJsonObject.keys()
        var tempSize = ""
        while (keys.hasNext()) {
            val key = keys.next()
            val value = rawJsonObject.optString(key)

            if (value.startsWith("http")) {
                downloadEntity.url = value
            } else if (value.endsWith("apk")) {
                downloadEntity.path = value
            } else if (value.startsWith("{\"")) {
                downloadEntity.meta = value.toObject()
                downloadEntity.name = downloadEntity.meta["game_name"]
            } else if (value == tempSize) {
                tryWithDefaultCatch {
                    downloadEntity.size = value.toLong()
                }
            } else {
                tempSize = value
            }
        }

        downloadEntity.status = DownloadStatus.done

        return downloadEntity
    }

}