package com.gamedog.vididin.manager

import com.ama.core.architecture.util.FileUtil
import com.gamedog.vididin.main.fragments.task.TaskBean
import com.google.gson.GsonBuilder
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.*

class TaskManager private constructor() {
    companion object {
        @Volatile
        private var instance: TaskManager? = null

        fun instance(): TaskManager {
            return instance ?: synchronized(this) {
                instance ?: TaskManager().also {
                    instance = it
                }
            }
        }
    }

    private val mutex = Mutex()

    @Volatile
    private var initialized = false
    private var mTaskConfigBean: TaskBean? = null
    private val mGson = GsonBuilder().create()


    init {
        loadTaskConfigAsync()
    }


    suspend fun getTaskConfig(): TaskBean? = mutex.withLock {
        if (!initialized) {
            loadTaskConfigFromAsset()
        }
        return mTaskConfigBean
    }

    private fun loadTaskConfigAsync() {
        CoroutineScope(Dispatchers.IO).launch {
            mutex.withLock {
                if (!initialized) {
                    loadTaskConfigFromAsset()
                }
            }
        }
    }

    private suspend fun loadTaskConfigFromAsset() {
        return withContext(Dispatchers.IO) {
            val configStr = FileUtil.readAssetsFile("taskConfig.json")
            mTaskConfigBean = mGson.fromJson(configStr, TaskBean::class.java)
            initialized = true
        }
    }
}


