package com.nexlab.openclaw.node.service

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.provider.Settings
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
import javax.inject.Singleton

/**
 * Service for clipboard operations
 */
@Singleton
class ClipboardService @Inject constructor(
    @ApplicationContext private val context: Context
) {
    private val clipboardManager: ClipboardManager = 
        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager

    /**
     * Copy text to clipboard
     */
    fun copyText(text: String, label: String = "OpenClaw") {
        val clip = ClipData.newPlainText(label, text)
        clipboardManager.setPrimaryClip(clip)
    }

    /**
     * Get text from clipboard
     */
    fun getText(): String? {
        return try {
            val clip = clipboardManager.primaryClip
            if (clip != null && clip.itemCount > 0) {
                clip.getItemAt(0).text?.toString()
            } else {
                null
            }
        } catch (e: Exception) {
            null
        }
    }

    /**
     * Check if clipboard has text
     */
    fun hasText(): Boolean {
        return try {
            clipboardManager.hasPrimaryClip() && 
            clipboardManager.primaryClipDescription?.hasMimeType(android.content.ClipDescription.MIMETYPE_TEXT_PLAIN) == true
        } catch (e: Exception) {
            false
        }
    }

    /**
     * Copy URI to clipboard
     */
    fun copyUri(uri: Uri, label: String = "OpenClaw") {
        val clip = ClipData.newUri(context.contentResolver, label, uri)
        clipboardManager.setPrimaryClip(clip)
    }

    /**
     * Clear clipboard
     */
    fun clear() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            clipboardManager.clearPrimaryClip()
        } else {
            @Suppress("DEPRECATION")
            clipboardManager.setPrimaryClip(ClipData.newPlainText("", ""))
        }
    }
}
