package com.sinch.android.rtc.sample.hmspush.hms

import android.content.Context
import android.os.AsyncTask
import android.util.Log
import com.huawei.agconnect.config.AGConnectServicesConfig
import com.huawei.hms.aaid.HmsInstanceId
import com.huawei.hms.common.ApiException
import com.sinch.android.rtc.sample.hmspush.hms.RegisterToHmsTask

class RegisterToHmsTask(
    private val context: Context,
    private val callback: RegistrationCallback
) :
    AsyncTask<Void, Void, Map<String, String>?>() {

    companion object {
        private val hmsApplicationIdKey = "HMS_APPLICATION_ID"
        private val hmsDeviceTokenKey = "HMS_DEVICE_TOKEN"
        private val TAG = RegisterToHmsTask::class.java.simpleName
    }

    override fun doInBackground(vararg params: Void): Map<String, String>? {
        var regId: MutableMap<String, String>? = null
        try {
            // read from agconnect-services.json
            val appId = AGConnectServicesConfig.fromContext(context).getString("client/app_id")
            val token = HmsInstanceId.getInstance(context).getToken(appId, "HCM")
            regId = HashMap()
            regId[hmsApplicationIdKey] = appId
            regId[hmsDeviceTokenKey] = token
            Log.i(TAG, "Get token result:$regId")
        } catch (e: ApiException) {
            Log.e(TAG, "Get token failed, $e")
        }
        return regId
    }

    override fun onPostExecute(regId: Map<String, String>?) {
        if (regId != null) {
            callback.onRegisterComplete(
                regId[hmsDeviceTokenKey],
                regId[hmsApplicationIdKey]
            )
        } else {
            callback.onRegisterComplete(null, null)
        }
    }

    interface RegistrationCallback {
        fun onRegisterComplete(deviceToken: String?, applicationId: String?)
    }

}