// ignore_for_file: avoid_print

import 'dart:io';
import 'dart:math';

import 'package:assets_audio_player/assets_audio_player.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:path_provider/path_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import '../interfaces/interfaces.dart';
import 'package:path/path.dart' as pathP;
import 'package:flutter/foundation.dart' show kIsWeb;

class AudioPlugin implements AudioInterface {
  final _soundRecorder = FlutterSoundRecorder();
  final _soundPlayer = AssetsAudioPlayer();
  bool _isRecorderReady = false;
  String? pathGlobal = '';

  @override
  Future<void> audioPauseAndResume() async {
    _soundPlayer.playOrPause();
  }

  @override
  Future audioPlay(File audio) async {
    _soundPlayer.open(
      Audio.file(audio.path),
      autoStart: true,
      showNotification: true,
    );
  }

  @override
  Future initSoundRecorder() async {
    final microfono = await Permission.microphone.request();
    if (microfono != PermissionStatus.granted) {
      throw 'Sin permiso de microfono';
    }
    await _soundRecorder.openRecorder();
    _isRecorderReady = true;
    await _soundRecorder.setSubscriptionDuration(
      const Duration(milliseconds: 500),
    );
  }

  Future<void> closeSoundRecorder() async {
    await _soundRecorder.closeRecorder();
  }

  @override
  Future startRecordAudio() async {
    print("1.-");
    if (!_isRecorderReady) return;
    await Permission.microphone.request();
    if (!kIsWeb) {
      await Permission.storage.request();
      await Permission.manageExternalStorage.request();
    }
    print("2.-");
    final random = Random();
    final randomInt = random.nextInt(99999);
    pathGlobal = '$randomInt.wav';
    print("3.-");
    if (!kIsWeb) {
      pathGlobal = '/$randomInt.wav';
      String directorio = (await getApplicationDocumentsDirectory()).path;
      Directory dir =
          Directory(pathP.dirname(directorio + pathGlobal.toString()));
      if (!dir.existsSync()) {
        dir.createSync();
      }
      pathGlobal = directorio + pathGlobal.toString();
      print("el global");
      print(pathGlobal);
    }
    print("4.-");

    await _soundRecorder.startRecorder(
      codec: Codec.pcm16WAV,
      numChannels: 1,
      sampleRate: 44000,
      toFile: pathGlobal.toString(),
    );
  }

  @override
  Future<File?> stopRecordAudio() async {
    if (!_isRecorderReady) return await Future.value(null);
    final path = await _soundRecorder.stopRecorder();
    return File(pathGlobal.toString());
  }

  bool isRecording() {
    if (_soundRecorder.isRecording) {
      return true;
    } else {
      return false;
    }
  }

  Stream<RecordingDisposition>? recordOnProgress() {
    return _soundRecorder.onProgress;
  }
}
