package com.adealink.weparty.imageselect.takePhoto

import android.content.res.Configuration
import android.view.View.GONE
import android.view.View.VISIBLE
import android.view.ViewAnimationUtils
import android.view.ViewGroup
import android.widget.ImageButton
import androidx.annotation.DrawableRes
import androidx.core.animation.doOnEnd
import androidx.core.animation.doOnStart

/**
 * @param flag 当前按钮状态
 */
fun ImageButton.toggleButton(
    flag: Boolean, rotationAngle: Float, @DrawableRes falseIcon: Int, @DrawableRes trueIcon: Int,
    action: (Boolean) -> Unit
) {
    // 计算目标旋转角度和对应图标
    val targetFlag = !flag
    val targetRotation = if (targetFlag) rotationAngle else 0f
    val targetIconRes = if (targetFlag) trueIcon else falseIcon

    // 执行旋转动画
    animate()
        .rotationY(targetRotation)
        .setDuration(200)
        .withEndAction {
            // 动画结束后同步更新图标和回调状态
            setImageResource(targetIconRes)
            action(targetFlag)
        }
        .start()
}

fun ViewGroup.circularReveal(button: ImageButton) {
    ViewAnimationUtils.createCircularReveal(
        this,
        button.x.toInt() + button.width / 2,
        button.y.toInt() + button.height / 2,
        0f,
        if (button.context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) this.width.toFloat() else this.height.toFloat()
    ).apply {
        duration = 500
        doOnStart { visibility = VISIBLE }
    }.start()
}

fun ViewGroup.circularClose(button: ImageButton, action: () -> Unit = {}) {
    ViewAnimationUtils.createCircularReveal(
        this,
        button.x.toInt() + button.width / 2,
        button.y.toInt() + button.height / 2,
        if (button.context.resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) this.width.toFloat() else this.height.toFloat(),
        0f
    ).apply {
        duration = 500
        doOnStart { action() }
        doOnEnd { visibility = GONE }
    }.start()
}
