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

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.os.Build
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.common.SharedPreferencesHelper
import cn.org.bjca.trust.push.db.DbHelper
import cn.org.bjca.trust.push.db.device.Device
import com.huawei.hms.push.HmsMessaging


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 {
        context?.let { SharedPreferencesHelper.getPreferences(it) }
        // 初始化数据库
        initDb()
        //初始化日志收集系统
        CrashHandler.init()
        // 初始化唯一码
        initDevice().let {
            when (it.manufacturer) {
                "HUAWEI" -> {
                    // 华为推送
                    try {
                        HmsMessaging.getInstance(context).isAutoInitEnabled = true
                    } catch (e: Exception) {
                        LogHelper.e("注册华为sdk失败", e)
                    }
                }
            }
        }


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

        return true
    }

    private fun initDevice(): Device {
        val devices = DbHelper.getDataBase().deviceDao().getAll()
        val device: Device?
        if (devices.isEmpty()) {
            device = Device()
            val fields = Build::class.java.declaredFields
            for (field in fields) {
                try {
                    field.isAccessible = true
                    when (field.name) {
                        "MANUFACTURER" -> device.manufacturer =
                            CommonHelper.anyToString(field[null])
                        "BRAND" -> device.brand = CommonHelper.anyToString(field[null])
                        "MODEL" -> device.model = CommonHelper.anyToString(field[null])
                        "CPU_ABI" -> device.cpuAbi = CommonHelper.anyToString(field[null])
                        "FINGERPRINT" -> {
                            device.fingerprint = CommonHelper.anyToString(field[null])
                            device.device = CommonHelper.anyToString(field[null])
                        }
                        "SUPPORTED_32_BIT_ABIS" -> device.supported32BitAbis =
                            CommonHelper.anyToString(field[null])
                        "SUPPORTED_64_BIT_ABIS" -> device.supported64BitAbis =
                            CommonHelper.anyToString(field[null])
                        "SUPPORTED_ABIS" -> device.supportedAbis =
                            CommonHelper.anyToString(field[null])
                    }
                } catch (e: Exception) {
                    LogHelper.e("an error occured when collect crash info", e)
                }
            }
            DbHelper.getDataBase().deviceDao().insertAll(device)
        } else {
            device = devices[0]
        }
        LogHelper.d(CommonHelper.anyToString(device))
        return 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
        }
    }

}