package com.atmob.keyboard_android.util

import android.annotation.SuppressLint
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ClipboardManager.OnPrimaryClipChangedListener
import android.content.Context
import android.content.Context.CLIPBOARD_SERVICE

/**
 * 剪切板工具类
 */
@SuppressLint("StaticFieldLeak")
object ClipboardHelper : OnPrimaryClipChangedListener {
    private val mContext = ContextUtil.getContext().applicationContext

    /**
     * 监听器列表
     */
    private val mListenerList = mutableListOf<OnUserClipboardDataUpdateListener>()

    interface OnUserClipboardDataUpdateListener {
        fun onUserClipboardDataUpdate(newText: String)
    }

    init {
        val clipboardManager = getClipboardManager(mContext)
        clipboardManager.addPrimaryClipChangedListener(this)
    }

    /**
     * 如果初始化时，就已经有复制内容了，则马上回调监听器
     */
    private fun firstInit() {
        val clipboardText = getUserClipboardData()
        if (clipboardText.isNotBlank()) {
            for (listener in mListenerList) {
                listener.onUserClipboardDataUpdate(clipboardText)
            }
        }
    }

    override fun onPrimaryClipChanged() {
        for (listener in mListenerList) {
            listener.onUserClipboardDataUpdate(getUserClipboardData())
        }
    }

    /**
     * 注册用户剪切板的数据监听
     */
    fun registerClipboardListener(listener: OnUserClipboardDataUpdateListener) {
        if (!mListenerList.contains(listener)) {
            mListenerList.add(listener)
        }
        firstInit()
    }

    /**
     * 取消注册用户剪切板的数据监听
     */
    fun unRegisterClipboardListener(listener: OnUserClipboardDataUpdateListener) {
        mListenerList.remove(listener)
    }

    /**
     * 获取用户剪切板的数据
     */
    fun getUserClipboardData(): String {
        val clipboardManager = getClipboardManager(mContext)
        val clip = clipboardManager.primaryClip
        // 处理剪切板内容
        if (clip != null && clip.itemCount > 0) {
            return clip.getItemAt(0).text?.toString() ?: ""
        }
        return ""
    }

    /**
     * 清空用户剪切板
     */
    fun clearClipboardData() {
        val clipboardManager = getClipboardManager(mContext)
        clipboardManager.setPrimaryClip(ClipData.newPlainText(null, ""))
    }

    /**
     * 获取剪切板管理器
     */
    private fun getClipboardManager(context: Context): ClipboardManager {
        return context.getSystemService(CLIPBOARD_SERVICE) as ClipboardManager
    }
}