package com.xyzshell.myphoneinfo.dialog

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.app.Dialog
import android.content.Context

import android.os.Bundle
import android.view.Gravity

import android.view.ViewGroup
import android.view.Window
import com.xyzshell.myphoneinfo.R

import com.xyzshell.myphoneinfo.databinding.ActivitySlideInPopViewBinding

class SlideInPopView(context: Context) : Dialog(context) {

    private lateinit var binding: ActivitySlideInPopViewBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 设置无标题
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        binding = ActivitySlideInPopViewBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 设置Dialog属性
        window?.apply {
            // 设置位置为左侧
            setGravity(Gravity.START)

            // 设置宽高
            val displayMetrics = context.resources.displayMetrics
            var width1 = (displayMetrics.widthPixels * 0.7).toInt()  // 70%屏幕宽度
            attributes = attributes?.apply {
                width = width1
                height = ViewGroup.LayoutParams.MATCH_PARENT

                // 设置动画
                windowAnimations = R.style.SlideInLeftAnimation
            }

            // 设置背景透明
            setBackgroundDrawableResource(android.R.color.transparent)
        }

        // 设置点击外部可以关闭
        setCanceledOnTouchOutside(true)

        setupViews()
        openSidebar()  // 打开时显示侧边栏
    }

    private fun setupViews() {
        // 侧边栏内的关闭按钮（如果有的话）
        // binding.btnClose.setOnClickListener { dismiss() }

        // 初始化侧边栏位置
        binding.root.post {
            binding.popupContent.translationX = -binding.popupContent.width.toFloat()
            openSidebar()
        }
    }

    private fun openSidebar() {
        val animator = ObjectAnimator.ofFloat(
            binding.popupContent,
            "translationX",
            -binding.popupContent.width.toFloat(),
            0f
        )
        animator.duration = 300
        animator.start()
    }

    private fun closeSidebar(callback: () -> Unit = {}) {
        val animator = ObjectAnimator.ofFloat(
            binding.popupContent,
            "translationX",
            0f,
            -binding.popupContent.width.toFloat()
        )
        animator.duration = 300
        animator.addListener(object : AnimatorListenerAdapter() {
            override fun onAnimationEnd(animation: Animator) {
                callback()
            }
        })
        animator.start()
    }

    override fun dismiss() {
        closeSidebar {
            super.dismiss()
        }
    }
}