import 'dart:io';

import 'package:electronic_assistant/base/base_controller.dart';
import 'package:electronic_assistant/router/app_pages.dart';
import 'package:electronic_assistant/utils/mmkv_util.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import '../dialog/desktop_shortcut_dialog.dart';
import 'android_shortcut.dart';

class DesktopShortcutUtils {
  DesktopShortcutUtils._();

  static const String routePath = 'route_path';

  static const String _showMaxTimeTag = 'showMaxTime';
  static const int _showMaxFrequency = 1;

  static Map<String, dynamic>? intentMap;

  static Future<void> registerDesktopShortcut() async {
    if (Platform.isAndroid) {
      androidShortCut.register();
    } else if (Platform.isIOS) {
      //TODO IOS
    }
  }

  static void isShowTipsDialog(void Function() nextCallback) {
    if (!_isShow()) {
      nextCallback();
      return;
    }
    showAddDesktopShortcutDialog(onConfirm: () {
      if (Platform.isAndroid) {
        showAddDesktopShortcutTipsDialog(onConfirm: () {
          androidShortCut.addRecordShortcut();
        }, onDismiss: () {
          nextCallback();
        });
      } else if (Platform.isIOS) {
        //TODO IOS
      }
    }, onCancel: () {
      nextCallback();
    });
    _setShowOnce();
  }

  static bool _isShow() {
    return KVUtil.getInt(_showMaxTimeTag, 0) < _showMaxFrequency;
  }

  static void _setShowOnce() {
    int maxFrequency = KVUtil.getInt(_showMaxTimeTag, 0);
    maxFrequency++;
    KVUtil.putInt(_showMaxTimeTag, maxFrequency);
  }

  static void requestAddDesktopShortcut() {
    if (Platform.isAndroid) {
      showAddDesktopShortcutTipsDialog(
          onConfirm: () {
            androidShortCut.addRecordShortcut();
          },
          onDismiss: () {});
    } else if (Platform.isIOS) {
      //TODO IOS
    }
  }

  static void setLaunchAction(String action) {
    intentMap ??= {};
    intentMap?[LaunchAction.key] = action;
  }

  static Map<String, dynamic>? getRouteMap() {
    return intentMap;
  }

  static void clearRouteMap() {
    intentMap = null;
  }

  static void setRouteAction(String recordAudioAction) {
    if (recordAudioAction == LaunchAction.recordAudioAction) {
      Get.toNamed(RoutePath.record);
    }
  }
}

class LaunchAction {
  static const String key = 'launchAction';
  static const String recordAudioAction = 'record_audio';
}
