import 'dart:io';

import 'package:flutter/services.dart';
import 'package:recording_tool/features/recording/platform/recording_channel_names.dart';

enum RecordingState {
  idle,
  previewing,
  recording,
  stopping,
  error;

  static RecordingState fromRaw(String? raw) {
    return RecordingState.values.firstWhere(
      (value) => value.name == raw,
      orElse: () => RecordingState.idle,
    );
  }
}

class RecordingStatus {
  const RecordingStatus({
    required this.state,
    this.streamUrl,
    this.elapsedMillis = 0,
    this.message,
  });

  final RecordingState state;
  final String? streamUrl;
  final int elapsedMillis;
  final String? message;

  factory RecordingStatus.fromMap(Map<dynamic, dynamic> map) {
    return RecordingStatus(
      state: RecordingState.fromRaw(map['state'] as String?),
      streamUrl: map['streamUrl'] as String?,
      elapsedMillis: (map['elapsedMillis'] as num?)?.toInt() ?? 0,
      message: map['message'] as String?,
    );
  }

  bool get isRecording => state == RecordingState.recording;
}

class RecordingPlatform {
  RecordingPlatform._();

  static const MethodChannel _channel = MethodChannel(
    RecordingChannelNames.method,
  );

  static bool get isSupported =>
      supportsHost(isAndroid: Platform.isAndroid, isIOS: Platform.isIOS);

  static bool supportsHost({required bool isAndroid, required bool isIOS}) {
    return isAndroid || isIOS;
  }

  static Future<bool> hasNotificationPolicyAccess() async {
    return await _channel.invokeMethod<bool>('hasNotificationPolicyAccess') ??
        false;
  }

  static Future<void> openNotificationPolicySettings() {
    return _channel.invokeMethod('openNotificationPolicySettings');
  }

  static Future<bool> enableDoNotDisturb() async {
    return await _channel.invokeMethod<bool>('enableDoNotDisturb') ?? false;
  }

  static Future<void> disableDoNotDisturb() {
    return _channel.invokeMethod('disableDoNotDisturb');
  }

  static Future<bool> isIgnoringBatteryOptimizations() async {
    return await _channel.invokeMethod<bool>(
          'isIgnoringBatteryOptimizations',
        ) ??
        true;
  }

  static Future<void> openBatteryOptimizationSettings() {
    return _channel.invokeMethod('openBatteryOptimizationSettings');
  }

  static Future<void> setImmersiveMode({required bool enabled}) {
    return _channel.invokeMethod('setImmersiveMode', <String, dynamic>{
      'enabled': enabled,
    });
  }
}
