package com.narutohuo.xindazhou.common.version.ui

import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.DialogFragment
import com.narutohuo.xindazhou.common.version.model.VersionResponse

/**
 * 版本更新对话框 Fragment
 */
class UpdateDialogFragment : DialogFragment() {
    
    private var versionResponse: VersionResponse? = null
    private var onDismiss: (() -> Unit)? = null
    
    companion object {
        fun create(
            versionResponse: VersionResponse,
            onDismiss: (() -> Unit)? = null
        ): UpdateDialogFragment {
            return UpdateDialogFragment().apply {
                this.versionResponse = versionResponse
                this.onDismiss = onDismiss
            }
        }
    }
    
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val info = versionResponse ?: return super.onCreateDialog(savedInstanceState)
        val builder = AlertDialog.Builder(requireContext())
        builder.setTitle("发现新版本")
        builder.setMessage("版本号: ${info.versionName}\n更新内容: ${info.versionDesc ?: "优化体验"}")
        
        if (info.forceUpdate == true) {
            // 强制更新，只能点击更新
            builder.setCancelable(false)
            builder.setPositiveButton("立即更新") { _, _ ->
                openDownloadUrl(info.downloadUrl)
                onDismiss?.invoke()
            }
        } else {
            // 可选更新
            builder.setPositiveButton("立即更新") { _, _ ->
                openDownloadUrl(info.downloadUrl)
                onDismiss?.invoke()
            }
            builder.setNegativeButton("稍后更新") { _, _ ->
                onDismiss?.invoke()
            }
        }
        
        return builder.create()
    }
    
    /**
     * 打开下载链接
     */
    private fun openDownloadUrl(downloadUrl: String?) {
        if (!downloadUrl.isNullOrEmpty()) {
            try {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(downloadUrl))
                startActivity(intent)
            } catch (e: Exception) {
                // 如果无法打开链接，忽略错误
            }
        }
    }
    
    override fun onDismiss(dialog: android.content.DialogInterface) {
        super.onDismiss(dialog)
        onDismiss?.invoke()
    }
}

