package com.ama.core.architecture.util

import android.content.Context
import android.os.Build
import android.provider.Settings
import com.ama.core.architecture.BaseApp
import java.util.*


class DeviceUtil private constructor() {

    companion object {

        /**
         * public method
         */
        fun generateDeviceId(): String {
            val hardwareUUID = getHardwareUUID()
            if (hardwareUUID.isNotBlank()) {
                return hardwareUUID
            }

            // way2
            val androidId = getAndroidId(BaseApp.appContext())
            if (androidId != null && isValidAndroidId(androidId)) {
                return UUID.nameUUIDFromBytes(androidId.toByteArray()).toString()
            }

            // final：there's no other better way
            return generateAndSaveRandomUUID(BaseApp.appContext())
        }

        /**
         * WAY-1 : Got uuid without any permissions, suggest this way
         */
        private fun getHardwareUUID(): String {
            return try {
                val hardwareInfo = StringBuilder().apply {
                    append(Build.BOARD)
                    append(Build.BRAND)
                    append(Build.DEVICE)
                    append(Build.HARDWARE)
                    append(Build.MANUFACTURER)
                    append(Build.MODEL)
                    append(Build.PRODUCT)
                }.toString()

                if (hardwareInfo.isNotBlank()) {
                    UUID.nameUUIDFromBytes(hardwareInfo.toByteArray()).toString()
                } else {
                    ""
                }
            } catch (e: Exception) {
                ""
            }
        }

        /**
         * WAY-2：got android_ids
         */
        private fun getAndroidId(context: Context): String? {
            return try {
                Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
            } catch (e: Exception) {
                null
            }
        }


        private fun isValidAndroidId(androidId: String): Boolean {
            return androidId.isNotBlank() &&
                    androidId != "0000000000000000" &&
                    androidId != "9774d56d682e549c"
        }

        /**
         * random uuid and save 2 sp to keep  the same value
         */
        private fun generateAndSaveRandomUUID(context: Context): String {
            val prefs = context.getSharedPreferences("device_id_prefs", Context.MODE_PRIVATE)
            var savedUuid = prefs.getString("device_uuid", null)

            if (savedUuid == null) {
                savedUuid = UUID.randomUUID().toString()
                prefs.edit().putString("device_uuid", savedUuid).apply()
            }

            return savedUuid
        }
    }
}