import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/l10n.dart';
import 'package:flutter_sound/flutter_sound.dart';
import 'package:intl/intl.dart';

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

  @override
  _RecordingDialogState createState() => _RecordingDialogState();
}

class _RecordingDialogState extends State<RecordingDialog> {
  FlutterSoundRecorder flutterSound = FlutterSoundRecorder();
  String time = '00:00:00';

  StreamSubscription _recorderSubscription;

  bool error = false;

  void startRecording() async {
    try {
      final recorder = await flutterSound.openAudioSession();
      await recorder.startRecorder();
      _recorderSubscription = flutterSound.onProgress.listen((disposition) {
        var date = DateTime.fromMillisecondsSinceEpoch(
            disposition.duration.inMilliseconds.toInt());
        setState(() => time = DateFormat('mm:ss:SS', 'en_US').format(date));
      });
    } catch (e) {
      error = true;
    }
  }

  @override
  void initState() {
    super.initState();
    startRecording();
  }

  @override
  void dispose() {
    if (flutterSound.isRecording) flutterSound.stopRecorder();
    _recorderSubscription?.cancel();
    flutterSound?.closeAudioSession();
    flutterSound = null;
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (error) {
      Timer(Duration(seconds: 1), () {
        Navigator.of(context).pop();
      });
    }
    return AlertDialog(
      content: Row(
        children: <Widget>[
          CircleAvatar(
            backgroundColor: Colors.red,
            radius: 8,
          ),
          SizedBox(width: 8),
          Expanded(
            child: Text(
              '${L10n.of(context).recording}: $time',
              style: TextStyle(
                fontSize: 18,
              ),
            ),
          ),
        ],
      ),
      actions: <Widget>[
        FlatButton(
          child: Text(
            L10n.of(context).cancel.toUpperCase(),
            style: TextStyle(
              color: Theme.of(context).textTheme.bodyText2.color.withAlpha(150),
            ),
          ),
          onPressed: () => Navigator.of(context).pop<String>(null),
        ),
        FlatButton(
          child: Row(
            children: <Widget>[
              Text(L10n.of(context).send.toUpperCase()),
              SizedBox(width: 4),
              Icon(Icons.send, size: 15),
            ],
          ),
          onPressed: () async {
            await _recorderSubscription?.cancel();
            await flutterSound.stopRecorder();
            Navigator.of(context).pop<String>(flutterSound.savedUri);
          },
        ),
      ],
    );
  }
}