package com.gh.gamecenter.provider

import android.content.*
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteException
import android.database.sqlite.SQLiteFullException
import android.database.sqlite.SQLiteOpenHelper
import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import com.gh.gamecenter.BuildConfig
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.core.utils.GsonUtils
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.ToastUtils
import com.gh.gamecenter.login.entity.UserInfoEntity
import com.gh.gamecenter.login.user.UserRepository
import com.halo.assistant.HaloApp
import com.lightgame.utils.Utils

class GhContentProvider : ContentProvider() {

    private var mUriMatcher: UriMatcher = UriMatcher(UriMatcher.NO_MATCH)
    private var mSqLiteDatabase: SQLiteDatabase? = null

    init {
        mUriMatcher.addURI(AUTHORITY, CERTIFICATION_TABLE_NAME, 1)
        mUriMatcher.addURI(AUTHORITY, SYNC_CERTIFICATION_TABLE_NAME, 2)
        mUriMatcher.addURI(AUTHORITY, DEVICE_TABLE_NAME, 3)
    }

    private fun initProviderSqliteHelper(context: Context?) {

        val helper: SQLiteOpenHelper =
            object : SQLiteOpenHelper(context, CERTIFICATION_DATABASE_NAME, null, 3) {
                override fun onCreate(db: SQLiteDatabase) {
                    val sql = "CREATE TABLE $CERTIFICATION_TABLE_NAME(" +
                            "$KEY_PRIMARY_KEY INTEGER PRIMARY KEY AUTOINCREMENT," +
                            "$KEY_IS_CERTIFICATED BOOL," +
                            "$KEY_IS_ADULT BOOL," +
                            "$KEY_IS_CERTIFICATING BOOL" +
                            ")"
                    db.execSQL(sql)

                    val syncSql = "CREATE TABLE ${SYNC_CERTIFICATION_TABLE_NAME}(" +
                            "$KEY_PRIMARY_KEY INTEGER PRIMARY KEY AUTOINCREMENT," +
                            "$KEY_REAL_NAME TEXT," +
                            "$KEY_ID_CARD TEXT" +
                            ")"
                    db.execSQL(syncSql)

                    val deviceSql = "CREATE TABLE ${DEVICE_TABLE_NAME}(" +
                            "$KEY_PRIMARY_KEY INTEGER PRIMARY KEY AUTOINCREMENT," +
                            "$KEY_GID TEXT," +
                            "$KEY_ANDROID_ID TEXT" +
                            ")"
                    db.execSQL(deviceSql)
                }

                override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
                    if (oldVersion == 1) {
                        val deviceSql = "CREATE TABLE ${DEVICE_TABLE_NAME}(" +
                                "$KEY_PRIMARY_KEY INTEGER PRIMARY KEY AUTOINCREMENT," +
                                "$KEY_GID TEXT," +
                                "$KEY_ANDROID_ID TEXT" +
                                ")"
                        db.execSQL(deviceSql)
                    }

                    if (oldVersion == 1 || oldVersion == 2) {
                        val addCertificatingColumnSql =
                            "ALTER TABLE $CERTIFICATION_TABLE_NAME ADD COLUMN $KEY_IS_CERTIFICATING BOOL DEFAULT FALSE"
                        db.execSQL(addCertificatingColumnSql)
                    }
                }
            }
        mSqLiteDatabase = helper.writableDatabase
    }

    override fun onCreate(): Boolean {
        try {
            val context = context ?: return false
            initProviderSqliteHelper(context)
        } catch (e: SQLiteException) {
            ToastUtils.toast("数据库内存已满，无法同步")
        }

        return true
    }

    override fun query(
        uri: Uri,
        projection: Array<out String>?,
        selection: String?,
        selectionArgs: Array<out String>?,
        sortOrder: String?
    ): Cursor? {
        when (mUriMatcher.match(uri)) {
            1 -> return mSqLiteDatabase?.query(
                CERTIFICATION_TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null
            )
            2 -> return mSqLiteDatabase?.query(
                SYNC_CERTIFICATION_TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null
            )
            3 -> return mSqLiteDatabase?.query(
                DEVICE_TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null
            )
        }
        return null

    }

    override fun getType(uri: Uri): String? = null


//    fun localInsert(context: Context,values: ContentValues?){
//        initProviderSqliteHelper(context)
//        try {
//            values?.put(KEY_PRIMARY_KEY, 1)
//            // 如果已存在则直接替换
//            mSqLiteDatabase?.insertWithOnConflict(
//                CERTIFICATION_TABLE_NAME,
//                null,
//                values,
//                SQLiteDatabase.CONFLICT_REPLACE
//            )
//
//        } catch (e: SQLiteFullException) {
//            Utils.toast(context,"数据库内存已满，无法同步")
//        }
//    }

    override fun insert(uri: Uri, values: ContentValues?): Uri? {
        val context = context ?: return null

        if (mUriMatcher.match(uri) == 1) {
            // 固定主键(只保留一条数据即可)
            try {
                values?.put(KEY_PRIMARY_KEY, 1)
                // 如果已存在则直接替换
                val rowId: Long? = mSqLiteDatabase?.insertWithOnConflict(
                    CERTIFICATION_TABLE_NAME,
                    null,
                    values,
                    SQLiteDatabase.CONFLICT_REPLACE
                )
                if (rowId != null && rowId > 0) {
                    val nameUri = ContentUris.withAppendedId(uri, rowId)
                    context.contentResolver.notifyChange(nameUri, null)
                    Utils.log(
                        "CertificationContentProvider",
                        "insert success:" + uri.authority + ", status => " + values?.toString()
                    )
                    return nameUri
                }
            } catch (e: SQLiteFullException) {
                Utils.toast(context, "数据库内存已满，无法同步")
            }

        } else if (mUriMatcher.match(uri) == 2) {
            val certificationStr =
                SPUtils.getString(Constants.SP_DEVICE_CERTIFICATION_PREFIX + HaloApp.getInstance().gid)
            val isCertification = if (TextUtils.isEmpty(certificationStr)) {
                false
            } else {
                val userInfo: UserInfoEntity =
                    GsonUtils.fromJson(certificationStr, UserInfoEntity::class.java)
                if (userInfo != null) {
                    !TextUtils.isEmpty(userInfo.idCard?.id)
                } else {
                    false
                }

            }
            if (!isCertification) {//如果未实名的话 就直接将写入的信息进行实名信息绑定
                val realName = values?.getAsString(KEY_REAL_NAME)
                val idCard = values?.getAsString(KEY_ID_CARD)
                if (!TextUtils.isEmpty(realName) && !TextUtils.isEmpty(idCard)) {
                    //base64解密存储的数据
                    val finalRealName = String(Base64.decode(realName, Base64.DEFAULT))
                    val finalIdCard = String(Base64.decode(idCard, Base64.DEFAULT))
//                    Utils.log("解密后的数据:$finalRealName ------ $finalIdCard")
                    //发送同步实名认证请求
                    UserRepository.getInstance().syncCertificate(finalRealName, finalIdCard)
                    return ContentUris.withAppendedId(uri, 1)
                }
            }
        } else if (mUriMatcher.match(uri) == 3) {
            try {
                // 固定主键(只保留一条数据即可)
                values?.put(KEY_PRIMARY_KEY, 1)
                // 如果已存在则直接替换
                val rowId: Long? = mSqLiteDatabase?.insertWithOnConflict(
                    DEVICE_TABLE_NAME,
                    null,
                    values,
                    SQLiteDatabase.CONFLICT_REPLACE
                )
                if (rowId != null && rowId > 0) {
                    val nameUri = ContentUris.withAppendedId(uri, rowId)
                    context.contentResolver.notifyChange(nameUri, null)
                    Utils.log(
                        "DeviceContentProvider",
                        "insert success:" + uri.authority + ", status => " + values?.toString()
                    )
                    return nameUri
                }
            } catch (e: SQLiteFullException) {
                Utils.toast(context, "数据库内存已满，无法同步")
            }
        }
        return null
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
        // delete from outside is forbidden
        if (mUriMatcher.match(uri) == 2) {
            return mSqLiteDatabase?.delete(SYNC_CERTIFICATION_TABLE_NAME, selection, selectionArgs) ?: 0
        }
        return 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String>?
    ): Int {
        return 0
    }

    companion object {
        private const val AUTHORITY = "${BuildConfig.APPLICATION_ID}.provider"
        private const val CERTIFICATION_DATABASE_NAME = "gh_certification.db"
        private const val CERTIFICATION_TABLE_NAME = "certification"
        private const val DEVICE_TABLE_NAME = "device"

        const val KEY_PRIMARY_KEY = "primary_key"
        const val KEY_IS_CERTIFICATED = "is_certificated"
        const val KEY_IS_CERTIFICATING = "is_certificating" // 是否正在认证中
        const val KEY_IS_ADULT = "is_adult"
        const val KEY_GID = "gid"
        const val KEY_ANDROID_ID = "android_id"

        private const val SYNC_CERTIFICATION_TABLE_NAME = "sync_certification"

        const val KEY_REAL_NAME = "real_name"
        const val KEY_ID_CARD = "id_card"
    }
}