import ClipData from "android.content.ClipData";
import ClipboardManager from "android.content.ClipboardManager";
import Context from "android.content.Context";
import { UTSAndroid } from "io.dcloud.uts";

import { SetClipboardDataOption, GetClipboardDataOption, GetClipboardDataSuccessCallbackOption } from '../interface.uts';
import { GeneralCallbackResultImpl } from '../unierror.uts';




export function setClipboardData(options : SetClipboardDataOption) {
	const handleClipboardOperationFailure = () => {
		const res = new GeneralCallbackResultImpl(9010002)
		options.fail?.(res)
		options.complete?.(res)
	}
	try {
		const context = UTSAndroid.getAppContext();
		if (context != null) {
			const clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager;
			const clip = ClipData.newPlainText('label', options.data);
			clipboard.setPrimaryClip(clip);
			const res = new GeneralCallbackResultImpl(9010001)
			if(options.showToast != false){
				uni.showToast({
					icon: 'success',
					title: '内容已复制'
				})
			}
			options.success?.(res)
			options.complete?.(res)
		} else {
			handleClipboardOperationFailure()
		}

	} catch (e) {
		handleClipboardOperationFailure()
	}

}


export function getClipboardData(options : GetClipboardDataOption) {
	const handleClipboardOperationFailure = () => {
		const res = new GeneralCallbackResultImpl(9010002, 'get')
		options.fail?.(res)
		options.complete?.(res)
	}
	try {
		const context = UTSAndroid.getAppContext();
		if (context != null) {
			const clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager;
			const clip = clipboard.getPrimaryClip();
			if (clip != null && clip.getItemCount() > 0) {
				const text = clip.getItemAt(0).getText();
				if (text != null) {
					options.success?.({
						data: text.toString(),
						errMsg: '成功'
					} as GetClipboardDataSuccessCallbackOption)

				} else {
					// 如果剪贴板没有文本数据，调用失败的处理函数
					handleClipboardOperationFailure();
				}
			} else {
				// 如果剪贴板没有内容，调用失败的处理函数
				handleClipboardOperationFailure();
			}
		} else {
			// 如果无法获取应用上下文，调用失败的处理函数
			handleClipboardOperationFailure();
		}

	} catch (e) {
		handleClipboardOperationFailure()
	}

}