import 'dart:async';
import 'dart:io';

import 'package:flutter_sound/flutter_sound.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tone_snap/routes/app_routes.dart';
import 'package:tone_snap/utils/date_util.dart';
import 'package:tone_snap/utils/local_path_util.dart';
import 'package:tone_snap/utils/permission_util.dart';

class RecordSoundController extends GetxController {
  final _recorder = FlutterSoundRecorder();

  /// isStopped:0, isPaused:1, isRecording:2
  var recorderState = 0.obs;

  /// 录音文件路径
  var _filePath = '';

  /// 计时器
  Timer? _timer;
  var recordDuration = 0.obs;

  @override
  void onInit() async {
    super.onInit();
    await _recorder.openRecorder();
  }

  @override
  void onClose() {
    _stopTimer();
    _recorder.closeRecorder();
    super.onClose();
  }

  void onTapRecord() {
    recorderState.value == 2 ? pauseRecording() : (recorderState.value == 1 ? resumeRecording() : startRecording());
  }

  /// 开始录音
  Future<void> startRecording() async {
    bool result = await PermissionUtil.checkPermission([Permission.microphone]);
    if (!result) return;

    Directory dir = await LocalPathUtil.getRecordingsDir();
    String path = '${dir.path}/${DateUtil.getNowTimestamp()}${ext[Codec.pcm16WAV.index]}';

    recordDuration.value = 0;
    await _recorder.startRecorder(
      toFile: path,
      codec: Codec.pcm16WAV,
      bitRate: 16000,
      numChannels: 1,
      sampleRate: 44100,
    );
    _startTimer();
    recorderState.value = 2;
    _filePath = path;
  }

  /// 恢复暂停的录音
  Future<void> resumeRecording() async {
    await _recorder.resumeRecorder();
    _startTimer();
    recorderState.value = 2;
  }

  /// 暂停录音
  Future<void> pauseRecording() async {
    await _recorder.pauseRecorder();
    _stopTimer();
    recorderState.value = 1;
  }

  /// 停止录音
  Future<void> stopRecording() async {
    await _recorder.stopRecorder();
    _stopTimer();
    recorderState.value = 0;
  }

  /// 开始定时器
  void _startTimer() {
    _timer = Timer.periodic(const Duration(seconds: 1), (Timer t) {
      recordDuration.value++;
      // 设置最大录音时长
      if (recordDuration.value >= 3600000) {
        stopRecording();
        return;
      }
    });
  }

  /// 停止定时器
  void _stopTimer() {
    _timer?.cancel();
    _timer = null;
  }

  /// 获取录制时长
  String getRecordDuration() {
    final duration = Duration(seconds: recordDuration.value);
    final minutes = duration.inMinutes.remainder(60);
    final secs = duration.inSeconds.remainder(60);
    return [
      if (minutes < 10) '0$minutes' else '$minutes',
      if (secs < 10) '0$secs' else '$secs'
    ].join(':');
  }

  String getRecordText() {
    if (recorderState.value == 0) {
      return 'Click to start';
    } else if (recorderState.value == 1) {
      return 'Click to continue';
    } else if (recorderState.value == 2) {
      return 'Click to pause';
    }
    return '';
  }

  bool showChangeVoice() {
    return (recorderState.value == 0 || recorderState.value == 1) && recordDuration.value > 0;
  }

  Future<void> goChangeVoice() async {
    _stopTimer();
    _recorder.closeRecorder();
    Get.offNamed(AppRoutes.changeVoice, arguments: _filePath);
  }
}