package cn.org.bjca.trust.push.provider

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.content.pm.PackageManager
import android.database.Cursor
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import androidx.sqlite.db.SupportSQLiteQueryBuilder
import cn.org.bjca.trust.push.CrashHandler
import cn.org.bjca.trust.push.common.CommonHelper
import cn.org.bjca.trust.push.common.LogHelper
import cn.org.bjca.trust.push.db.DbHelper
import cn.org.bjca.trust.push.db.device.Device
import com.huawei.hms.aaid.HmsInstanceId
import com.huawei.hms.common.ApiException
import com.huawei.hms.push.HmsMessaging
import com.xiaomi.push.it


class PushProvider : ContentProvider() {

    private val matcher by lazy { UriMatcher(UriMatcher.NO_MATCH) }

    companion object {
        const val authority = "cn.org.bjca.trust.pushdemo.szyx.push" // 用于 contentUri, 用于 manifest
        const val contentUriStr = "content://$authority"

        private const val TABLE_DEVICE = "device"
        private const val FUNC_DEVICE_ALL = 10
    }

    override fun onCreate(): Boolean {
        // 初始化数据库
        initDb()
        //初始化日志收集系统
        CrashHandler.init()
        // 初始化唯一码
        initDevice()
//getHwToken()
        HmsMessaging.getInstance(context).isAutoInitEnabled = true

//        MiPushClient.registerPush(this, APP_ID, APP_KEY);

        return true
    }

    private fun initDevice() {
        val device = DbHelper.getDataBase().deviceDao().getAll()
        if (device.isEmpty()) {
            DbHelper.getDataBase().deviceDao().insertAll(Device(1, "ryctvbnml;feakbfveugavhb "))
        }
        LogHelper.e(CommonHelper.anyToString(device))
    }

    private fun initDb() {
        DbHelper.getDataBase(context!!)
        matcher.addURI(authority, "device/all", FUNC_DEVICE_ALL)
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        val flag = when (matcher.match(uri)) {
            FUNC_DEVICE_ALL -> true
            else -> false
        }
        if (!flag) return null // 不符合uri规则就退出；否则 若是一个没有预定义的 uri，后续操作会引发错误

        val table = getTableName(uri)
        return if (table != null) DbHelper.getDataBase().openHelper.readableDatabase.query(
            SupportSQLiteQueryBuilder.builder(table)
                .selection(selection, selectionArgs)
                .columns(projection)
                .orderBy(sortOrder)
                .create()
        ) else null
    }

    override fun getType(uri: Uri): String? {
        TODO("Not yet implemented")
    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        TODO("Not yet implemented")
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        TODO("Not yet implemented")
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        TODO("Not yet implemented")
    }

    // 根据 uri，匹配出对应的数据表
    private fun getTableName(uri: Uri): String? {
        return when (matcher.match(uri)) {
            FUNC_DEVICE_ALL -> TABLE_DEVICE
            else -> null
        }
    }

    // 华为相关
    private fun getHwToken() {
        // 创建一个新线程
        object : Thread() {
            override fun run() {
                try {


                    val appId = context!!.packageManager.getApplicationInfo(
                        context!!.packageName,
                        PackageManager.GET_META_DATA
                    ).metaData.getString("HUAWEI_APP_ID")?.substring(1)
                    LogHelper.e("appId:$appId")

                    // 输入token标识"HCM"
                    val tokenScope = "HCM"
                    val token = HmsInstanceId.getInstance(context).getToken(appId, tokenScope)
                    LogHelper.e("get token:$token")

                    // 判断token是否为空
//                    if (!TextUtils.isEmpty(token)) {
////                        sendRegTokenToServer(token)
//                    }
                } catch (e: ApiException) {
                    LogHelper.e("get token failed, $e")
                }
            }
        }.start()
    }
}