package com.waytous.anticollision.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.drawable.Drawable
import android.os.Build
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.graphics.drawable.DrawableCompat


/**
 * 连接状态
 * */
enum class ConnectStatus {
    Disconnected, Connected
}

/**
 * 登录状态
 * */
enum class SignInStatus {
    SignOut, SignIn
}

/**
 * tcp通信错误定义
 * */
enum class Error(val reason:String = "success") {
    NOError,
    IOError("io error"),
    StreamClosed("stream closed"),
    ConnectionRefused("connection refused"),
    Timeout("time out"),
    NotConnected("not connected"),
    UserDisconnected("user disconnected"),
    InvalidParam("invalid param"),
    ServerUnknownError("server unknown error"),
    JT808EncodeError("jt808 codec encode error"),
    JT808DecodeError("jt808 codec decode error")
}

fun TextView.setTextSize(spannableString: SpannableString,content:String,delimiter:String = "km"){
    val absoluteSizeSpan = AbsoluteSizeSpan(40,true)
    spannableString.setSpan(absoluteSizeSpan,0,content.indexOf(delimiter),Spannable.SPAN_INCLUSIVE_EXCLUSIVE)
    text = spannableString
}

fun Context.getBitmapFromVectorDrawable(drawableId:Int,scale:Int = 2): Bitmap? {
    val drawable: Drawable? = ContextCompat.getDrawable(this, drawableId)
    val bitmap = drawable?.intrinsicWidth?.let {
        Bitmap.createBitmap(
            it/scale, drawable.intrinsicHeight/scale,
            Bitmap.Config.ARGB_8888
        )
    }
    bitmap?.let { Canvas(it).also {canvas->
        drawable.setBounds(0, 0, canvas.width, canvas.height)
        drawable.draw(canvas)
    } }
    return bitmap
}

fun AppCompatActivity.checkSelfPermissionCompat(permission: String) =
    ActivityCompat.checkSelfPermission(this, permission)

fun AppCompatActivity.shouldShowRequestPermissionRationaleCompat(permission: String) =
    ActivityCompat.shouldShowRequestPermissionRationale(this, permission)

fun AppCompatActivity.requestPermissionsCompat(permissionsArray: Array<String>,
                                               requestCode: Int) {
    ActivityCompat.requestPermissions(this, permissionsArray, requestCode)
}

