import 'dart:io';

import 'package:SEFER/controller/home/map_passenger_controller.dart';
// import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';

import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:record/record.dart';

class AudioRecorderController extends GetxController {
  AudioPlayer audioPlayer = AudioPlayer();
  AudioRecorder recorder = AudioRecorder();

  bool isRecording = false;
  String filePath = '';
  String? selectedFilePath;
  double currentPosition = 0;
  double totalDuration = 0;
  String? selectedFile;

  Future<void> startRecording() async {
    final bool isPermissionGranted = await recorder.hasPermission();
    if (!isPermissionGranted) {
      // RecordingPermissionException('l');
      print('sss');
      return;
    }

    final directory = await getApplicationDocumentsDirectory();
    // Generate a unique file name using the current timestamp
    String fileName =
        '${DateTime.now().year}-${DateTime.now().month}-${DateTime.now().day}_${Get.find<MapPassengerController>().rideId}.m4a';
    filePath = '${directory.path}/$fileName';

    // Define the configuration for the recording
    const config = RecordConfig(
      // Specify the format, encoder, sample rate, etc., as needed
      encoder: AudioEncoder.aacLc, // For example, using AAC codec
      sampleRate: 44100, // Sample rate
      bitRate: 128000, // Bit rate
    );

    // Start recording to file with the specified configuration
    await recorder.start(config, path: filePath);

    isRecording = true;
    update();
  }

  Future<void> stopRecording() async {
    final path = await recorder.stop();
    print(path);
    isRecording = false;
    update();
  }

  Future<void> playRecording() async {
    if (filePath != null) {
      await audioPlayer.setFilePath(filePath!);
      totalDuration = audioPlayer.duration?.inSeconds.toDouble() ?? 0;
      audioPlayer.play();

      audioPlayer.positionStream.listen((position) {
        currentPosition = position.inSeconds.toDouble();
      });
      selectedFilePath = filePath;
      update();
    }
  }

  Future<List<String>> getRecordedFiles() async {
    final directory = await getApplicationDocumentsDirectory();
    final files = await directory.list().toList();
    return files
        .map((file) => file.path)
        .where((path) => path.endsWith('.m4a'))
        .toList();
  }

  Future<void> playRecordedFile(String filePath) async {
    await audioPlayer.setFilePath(filePath);
    totalDuration = audioPlayer.duration?.inSeconds.toDouble() ?? 0;
    audioPlayer.play();

    audioPlayer.positionStream.listen((position) {
      currentPosition = position.inSeconds.toDouble();
    });
    update();
  }

  Future<void> deleteRecordedFile(String filePath) async {
    final file = File(filePath);
    if (await file.exists()) {
      await file.delete();
      print('File deleted: $filePath');
      await getRecordedFiles();
    } else {
      print('File not found: $filePath');
    }
  }

  Future<void> deleteAllRecordedFiles() async {
    final directory = await getApplicationDocumentsDirectory();
    final files = await directory.list().toList();
    for (final file in files) {
      if (file.path.endsWith('.m4a')) {
        await deleteRecordedFile(file.path);
      }
    }
  }

  @override
  void onClose() {
    audioPlayer.dispose();
    recorder.dispose();
    super.onClose();
  }
}
