package com.rc.core.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.pm.PackageManager
import java.io.IOException
import kotlin.math.roundToInt

/**
 * info
 *
 * @author ReiChin_
 */
object DeviceUtils {

    /**
     * 获取系统SN序列号
     */
    @SuppressLint("PrivateApi")
    fun getAndroidSN(defSN: String = "NULL"): String {
        return try {
            val sysClass = Class.forName("android.os.SystemProperties")
            sysClass.getMethod("get", String::class.java, String::class.java)
                .invoke(sysClass, "ro.serialno", defSN) as? String ?: defSN
        } catch (e: Exception) {
            e.printStackTrace()
            defSN
        }
    }

    /**
     * 获取当前apk版本名称(versionName)
     */
    fun getVersionName(context: Context): String {
        return try {
            // 获取包信息
            // 参1 包名 参2 获取额外信息的flag 不需要的话 写0
            context.packageManager.getPackageInfo(
                context.packageName, 0
            ).versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            ""
        }
    }

    /**
     * 获取当前apk版本号(versionCode)
     */
    fun getVersionCode(context: Context): Int {
        return try {
            context.packageManager.getPackageInfo(context.packageName, 0).versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            -1
        }
    }

    /**
     * 提升读写权限
     *
     * @param filePath 文件路径
     */
    fun promotePermission(filePath: String) {
        val command = "chmod 777 $filePath"
        val runtime = Runtime.getRuntime()
        try {
            runtime.exec(command)
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    fun dip2px(context: Context, dpValue: Float): Int {
        val scale = context.resources.displayMetrics.density
        return (dpValue * scale + 0.5f).toInt()
    }

    fun spanCount(context: Context, gridExpectedSize: Int, offset: Int, horizontalSpacing: Int): Int {
        val screenWidth = context.resources.displayMetrics.widthPixels - offset + horizontalSpacing
        val expected = screenWidth.toFloat() / (gridExpectedSize.toFloat() + horizontalSpacing)
        var spanCount = expected.roundToInt()
        if (spanCount == 0) {
            spanCount = 1
        }
        return spanCount
    }

}