package com.remax.visualnovel.extension

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Typeface
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Handler
import android.os.Looper
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.core.graphics.scale
import com.remax.visualnovel.BuildConfig
import com.remax.visualnovel.R
import com.remax.visualnovel.app.base.BaseBindingActivity
import com.remax.visualnovel.utils.StatusBarUtils
import com.remax.visualnovel.utils.spannablex.utils.dp
import com.remax.visualnovel.widget.uitoken.handleUIToken
import com.dylanc.loadingstateview.BgColorType
import com.remax.visualnovel.manager.CustomToastManager
import dagger.hilt.android.internal.managers.FragmentComponentManager
import timber.log.Timber
import java.io.IOException

/**
 * context扩展方法
 */

/**
 * 获取标题栏高度
 * navheight + 是否显示状态栏?:状态栏高度 or 0
 */
fun Context.getNavHeight(isFullScreen: Boolean = true) =
    resources.getDimensionPixelSize(R.dimen.nav_height) + if (isFullScreen) StatusBarUtils.statusBarHeight else 0


/**
 * 在fragment中使用，hilt注解库将fragment的context进行了包装
 * 外面需要判断强转
 */
fun Context.findActivityContext(): Context {
    return FragmentComponentManager.findActivity(this)
}

fun Context.findBaseActivity(): BaseBindingActivity<*>? = findActivityContext() as? BaseBindingActivity<*>

/**
 * 快速设置状态栏颜色
 * color.background.specialmap
 * color.background.district
 * color.background.default
 */
fun Context.getBgColor(bgColorType: BgColorType = BgColorType.SPECIAL_MAP): Int {
    return when (bgColorType) {
        BgColorType.DEFAULT -> {
            handleUIToken(R.string.color_background_default)?.color ?: 0
        }

        BgColorType.DISTRICT -> {
            handleUIToken(R.string.color_background_district)?.color ?: 0
        }

        BgColorType.SPECIAL_MAP -> {
            handleUIToken(R.string.color_background_specialmap)?.color ?: 0
        }

        BgColorType.TRANSPARENT -> {
            handleUIToken(R.string.color_transparent)?.color ?: 0
        }
    }
}

fun Activity.setStatusBarColor(bgColorType: BgColorType = BgColorType.SPECIAL_MAP) {
    val color = getBgColor(bgColorType)
    StatusBarUtils.setColor(this, color)
}

/**
 * 返回iconFont的typeface
 */
private var iconFontTypeface: Typeface? = null
fun Context.getIconFontType(): Typeface {
    if (iconFontTypeface == null) {
        iconFontTypeface = Typeface.createFromAsset(assets, "iconfont/iconfont.ttf")
    }
    return iconFontTypeface!!
}

private var D_Din_700: Typeface? = null
private var Bangers_400: Typeface? = null
private var Poppins_400: Typeface? = null
private var Poppins_500: Typeface? = null
private var Poppins_600: Typeface? = null
private var Poppins_700: Typeface? = null

const val D_Din_700_typeface = "family/D-Din-700.ttf"
const val Bangers_400_typeface = "family/Bangers-400.ttf"
const val Poppins_400_typeface = "family/Poppins-400.ttf"
const val Poppins_500_typeface = "family/Poppins-500.ttf"
const val Poppins_600_typeface = "family/Poppins-600.ttf"
const val Poppins_700_typeface = "family/Poppins-700.ttf"

/**
 * 缓存字体包
 * @receiver Context
 * @param typeface String?
 * @return Typeface
 */
fun Context.getTextFontTypeface(typeface: String?): Typeface {
    return when (typeface) {
        Poppins_400_typeface -> {
            if (Poppins_400 == null) {
                Poppins_400 = Typeface.createFromAsset(assets, typeface)
            }
            Poppins_400 ?: Typeface.createFromAsset(assets, typeface)
        }

        Poppins_500_typeface -> {
            if (Poppins_500 == null) {
                Poppins_500 = Typeface.createFromAsset(assets, typeface)
            }
            Poppins_500 ?: Typeface.createFromAsset(assets, typeface)
        }

        Poppins_600_typeface -> {
            if (Poppins_600 == null) {
                Poppins_600 = Typeface.createFromAsset(assets, typeface)
            }
            Poppins_600 ?: Typeface.createFromAsset(assets, typeface)
        }

        Poppins_700_typeface -> {
            if (Poppins_700 == null) {
                Poppins_700 = Typeface.createFromAsset(assets, typeface)
            }
            Poppins_700 ?: Typeface.createFromAsset(assets, typeface)
        }

        D_Din_700_typeface -> {
            if (D_Din_700 == null) {
                D_Din_700 = Typeface.createFromAsset(assets, typeface)
            }
            D_Din_700 ?: Typeface.createFromAsset(assets, typeface)
        }

        Bangers_400_typeface -> {
            if (Bangers_400 == null) {
                Bangers_400 = Typeface.createFromAsset(assets, typeface)
            }
            Bangers_400 ?: Typeface.createFromAsset(assets, typeface)
        }

        else -> {
            Typeface.createFromAsset(assets, typeface)
        }
    }
}

fun Context.toast(msg: String?, isLong: Boolean = false) {
    Handler(Looper.getMainLooper()).post {
        CustomToastManager.showToast(this, msg, isLong)
    }
}

fun Context.toast(@StringRes msg: Int, isLong: Boolean = false) {
    toast(getString(msg), isLong)
}

/**
 * 复制到剪切板
 */
fun Context.copyLink(link: String?) {
    if (link == null) return
    val cm = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
    val data = ClipData.newPlainText("Label", link)
    cm.setPrimaryClip(data)
    toast(getString(R.string.copy_successful))
}

@Throws(IOException::class)
fun Context.readJsonAsset(fileName: String): String {
    val inputStream = assets.open(fileName)
    val size = inputStream.available()
    val buffer = ByteArray(size)
    inputStream.read(buffer)
    inputStream.close()
    return String(buffer, Charsets.UTF_8)
}


/**
 * 打开外部浏览器
 * alternateUrl:备用地址 外部应用不存在的情况下调至备用页面
 */
fun Context.jumpBrowser(url: String?, alternateUrl: String? = null) {
    runCatching {
        var realUrl = url ?: ""
        if (realUrl.isNotBlank()) {
            if (!realUrl.startsWith("http://") && !realUrl.startsWith("https://")) {
                realUrl = "http://$realUrl"
            }
            val uri = Uri.parse(realUrl)
            Intent(Intent.ACTION_VIEW, uri).apply {
                flags = Intent.FLAG_ACTIVITY_NEW_TASK
                startActivity(this)
            }
        }
    }.onFailure {
        alternateUrl?.let(::jumpBrowser)
    }
}

/**
 * 调用系统分享
 */
fun Context.jumpShare(aiId: String?) {
    try {
        val intent = Intent(Intent.ACTION_SEND)
        intent.type = "text/plain"
        val url = "${BuildConfig.HOST}@$aiId"
        intent.putExtra(Intent.EXTRA_TEXT, url)
        startActivity(Intent.createChooser(intent, getString(R.string.share)))
    } catch (e: Exception) {
        Timber.e(e)
    }
}


/**
 * 创建一个大小固定的bitmap
 */
fun Context.createScaledBitmap(@DrawableRes drawableRes: Int, size: Int? = null): Bitmap =
    if (size != null) {
        (ContextCompat.getDrawable(this, drawableRes) as BitmapDrawable).bitmap.scale(size.dp, size.dp, false)
    } else {
        Bitmap.createBitmap((ContextCompat.getDrawable(this, drawableRes) as BitmapDrawable).bitmap)
    }


