package com.grkj.iscs_mc.util

import android.content.Context
import android.os.Environment
import android.text.method.HideReturnsTransformationMethod
import android.text.method.PasswordTransformationMethod
import android.widget.EditText
import android.widget.ImageView
import cn.zhxu.data.TypeRef
import cn.zhxu.okhttps.HttpResult
import com.google.gson.Gson
import com.grkj.iscs_mc.model.vo.BaseVO
import java.io.Closeable
import java.io.File


val gson = Gson()

/**
 * 虚拟机相对时间（秒）
 */
fun jvmSeconds() : Long {
    return System.nanoTime() / 1000_000_000
}

/**
 * 当前时间（秒）
 */
fun nowSeconds() : Long {
    return System.currentTimeMillis() / 1000
}


val EXT_ROOT_PATH : String = Environment.getExternalStorageDirectory().absolutePath

fun extFile(path: String) : File {
    return File(EXT_ROOT_PATH + File.separator + "refuse-class" + File.separator + path)
}

fun fileRootPath() : String {
    return EXT_ROOT_PATH + File.separator + "refuse-class"
}


fun Closeable.closeQuietly() {
    try {
        close()
    } catch (rethrown: RuntimeException) {
        throw rethrown
    } catch (_: Exception) {
    }
}

fun dp2px(context: Context, dpValue: Float): Int {
    val scale: Float = context.resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}

fun px2dp(context: Context, pxValue: Float): Int {
    val scale: Float = context.resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

inline fun <reified T> getRef(): TypeRef<BaseVO<T>> {
    return object : TypeRef<BaseVO<T>>() {}
}

inline fun <reified T> getBaseVO(rst: HttpResult.Body): BaseVO<T>? {
    return rst.toBean(getRef<T>())
}

inline fun <reified T> getRefBean(rst: HttpResult.Body): T? {
    return rst.toBean(getRef<T>()).data
}

/**
 * 密码显示效果切换
 * @param view：输入控件
 * @param imageView：明文和密文icon控件。selected属性
 */
fun passwordStyle(view: EditText?, imageView: ImageView) {
    if (imageView.isSelected) {
        view?.transformationMethod = PasswordTransformationMethod.getInstance()
    } else {
        view?.transformationMethod = HideReturnsTransformationMethod.getInstance()
    }
    view?.setSelection(view.text.toString().length)
    imageView.isSelected = !imageView.isSelected
}

fun byteToHexString(byte: Byte): String {
    return "0x%02X".format(byte)
}