part of record;


typedef _Fn = void Function();

const theSource = AudioSource.microphone;

class RecordPage extends StatefulWidget {
  const RecordPage({Key? key}) : super(key: key);

  @override
  State<RecordPage> createState() => _RecordPageState();
}

class _RecordPageState extends State<RecordPage> {
  final FlutterSoundRecorder? _mRecorder = FlutterSoundRecorder();
  final FlutterSoundPlayer? _mPlayer = FlutterSoundPlayer();
  final String _mPath = 'tau_file.mp4';
  final Codec _codec = Codec.aacMP4;
  bool _mRecorderIsInited = false;


  @override
  void initState() {
    openTheRecorder().then((value) {
      setState(() {
        _mRecorderIsInited = true;
      });
    });
    super.initState();
  }



  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.blue,
      appBar: AppBar(
        title: const Text('Recorder'),
      ),
      body: Column(
        children: [
          Container(
            margin:  EdgeInsets.all(3.w),
            padding: EdgeInsets.all(3.w),
            height: 80.w,
            width: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(
                color: Colors.indigo,
                width: 3
              )
            ),
            child: Row(
              children: [
                ElevatedButton(
                    onPressed: getRecorderFn(),
                    child: Text(_mRecorder!.isRecording?'stop':'Record')
                ),
                SizedBox(
                  width: 20.w,
                ),
                Text(_mRecorder!.isRecording? 'Recording in progress' : 'Record is stopped')
              ],
            ),
          ),
          Container(
            margin:  EdgeInsets.all(3.w),
            padding:  EdgeInsets.all(3.w),
            height: 80,
            width: double.infinity,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: Color(0xFFFAF0E6),
              border: Border.all(
                color: Colors.indigo,
                width: 3,
              ),
            ),
            child: Row(children: [
              ElevatedButton(
                onPressed: (){

                },
                //color: Colors.white,
                //disabledColor: Colors.grey,
                child: Text(_mPlayer!.isPlaying ? 'Stop' : 'Play'),
              ),
              SizedBox(
                width: 20,
              ),
              Text(_mPlayer!.isPlaying
                  ? 'Playback in progress'
                  : 'Player is stopped'),
            ]),
          )
        ],
      ),
    );

  }

  Future<void> openTheRecorder() async {
    Permission permission = Permission.microphone;
    var status = await permission.request();
    if (status != PermissionStatus.granted){
      throw RecordingPermissionException('Microphone permission not granted');
    }else if (status == PermissionStatus.denied) {
        requestPermission(permission);
    } else if(status == PermissionStatus.permanentlyDenied){
      requestPermission(permission);
    } else if(status == PermissionStatus.restricted){
      requestPermission(permission);
    }
    await _mRecorder!.openRecorder();

    final session = await AudioSession.instance;
    await session.configure(AudioSessionConfiguration(
      avAudioSessionCategory: AVAudioSessionCategory.playAndRecord,
      avAudioSessionCategoryOptions:
      AVAudioSessionCategoryOptions.allowBluetooth |
      AVAudioSessionCategoryOptions.defaultToSpeaker,
      avAudioSessionMode: AVAudioSessionMode.spokenAudio,
      avAudioSessionRouteSharingPolicy:
      AVAudioSessionRouteSharingPolicy.defaultPolicy,
      avAudioSessionSetActiveOptions: AVAudioSessionSetActiveOptions.none,
      androidAudioAttributes: const AndroidAudioAttributes(
        contentType: AndroidAudioContentType.speech,
        flags: AndroidAudioFlags.none,
        usage: AndroidAudioUsage.voiceCommunication,
      ),
      androidAudioFocusGainType: AndroidAudioFocusGainType.gain,
      androidWillPauseWhenDucked: true,
    ));
    _mRecorderIsInited = true;

  }

  _Fn? getRecorderFn() {
    if (!_mRecorderIsInited){
      return null;
    }
    return _mRecorder!.isStopped ? record : stopRecorder;
  }

  void record() async {
    Directory? tempDir = await getExternalStorageDirectory();
    var time = DateTime.now().millisecondsSinceEpoch;
    const String mPath = 'tau_file.mp4';
    String filePath = '${tempDir!.path}/$time$mPath';
    _mRecorder!.startRecorder(
      toFile: filePath,
      codec: _codec,
      audioSource: theSource
    ).then((value) {
      setState(() {});
    });
  }
  void stopRecorder() async{
    await _mRecorder!.stopRecorder().then((value) async {
      Directory? tempDir = await getExternalStorageDirectory();
      List<FileSystemEntity> files = tempDir!.listSync();

      for (FileSystemEntity file in files) {
        print('File: ${file.path}');
      }
      setState(() {

      });
    });
  }
  void requestPermission(Permission permission) async {
    PermissionStatus status = await permission.request();
    if (status.isPermanentlyDenied){
      openAppSettings();
    }
  }
}
