import { ConfigManager } from '../manager/UserConfigManager';
import { pasteboard } from '@kit.BasicServicesKit';
import { preferences } from '@kit.ArkData';

export class PasteboardUtils {
  private static systemPasteboard: pasteboard.SystemPasteboard = pasteboard.getSystemPasteboard();
  private static patterns: pasteboard.Pattern[] = [pasteboard.Pattern.URL, pasteboard.Pattern.EMAIL_ADDRESS];
  private static dataPreferences: preferences.Preferences | null = null;

  static clipText?: string

  static async isNeedGetPermissionFromUser(): Promise<boolean> {
    try {
      let hasData: boolean = await PasteboardUtils.systemPasteboard.hasData()
      if (!hasData) {
        // 剪贴板不存在数据，无需申请权限
        return false
      }
      // 获取剪贴板的内容变化次数
      let result: number = PasteboardUtils.systemPasteboard.getChangeCount()
      // 从 Preferences 中读取上次保存的 changeCount
      let storedChangeCount: number = PasteboardUtils.dataPreferences ? Number(PasteboardUtils.dataPreferences.getSync('pasteboardChangeCount', 0)) : 0
      if (result === storedChangeCount) {
        // 剪贴板无数据变化，无需申请权限
        return false
      }
    } catch (err) {
      return false
    }

    // 查询剪贴板是否存在应用所需数据类型
    try {
      // (可选)判断是否有应用需要的数据类型
      let result: boolean = PasteboardUtils.systemPasteboard.hasDataType(pasteboard.MIMETYPE_TEXT_PLAIN)
      if (!result) {
        // 剪贴板不存在应用所需数据类型，无需申请权限
        return false
      }
      // (可选)涉及口令等应用自身特殊复制内容的，使用detectPatterns过滤口令格式
      let data: pasteboard.Pattern[] = await PasteboardUtils.systemPasteboard.detectPatterns(PasteboardUtils.patterns)
      if (PasteboardUtils.patterns.sort().join('') != data.sort().join('')) {
        return false
      }
    } catch (err) {
      return false
    }
    return true
  }

  /**
   * 是否是有效链接
   */
  static isValidUrl(text: string): boolean {
    let isValid = false
    for (let i = 0;i < ConfigManager.getCopyContainsList().length;i++) {
      if (text.includes(ConfigManager.getCopyContainsList()[i])) {
        isValid = true
        break
      }
    }
    return isValid
  }
}