/// apicall
import 'dart:convert';

import 'package:just_audio/just_audio.dart';
import 'package:rxdart/rxdart.dart';
import 'package:voice_buddies/app/models/login_model.dart';
import 'package:voice_buddies/app/widget/base_controller.dart';

import '../../../models/message_model.dart';
import '../../../utils/all_imports.dart';
import '../../../widget/common_seekbar.dart';

class FlagController extends BaseController {
  TextEditingController message = TextEditingController();
  final player = AudioPlayer();

  MessageData messages = MessageData();

  @override
  Future<void> onInit() async {
    if (Get.arguments != null) {
      printAction(jsonEncode(Get.arguments));
      messages = Get.arguments;
    }
    if (messages.msg!.isURL) {
      await player.setAudioSource(AudioSource.uri(Uri.parse(messages.msg!)));
    } else {
      printAction("elsee m,a aache cheoibu");
      await player.setAudioSource(AudioSource.file(messages.msg!));
    }
    super.onInit();
  }

  Stream<PositionData> get positionDataStream {
    return Rx.combineLatest3<Duration, Duration, Duration?, PositionData>(
      player.positionStream,
      player.bufferedPositionStream,
      player.durationStream,
      (position, bufferedPosition, duration) => PositionData(
        position,
        bufferedPosition,
        duration ?? Duration.zero,
      ),
    );
  }

  /// addFlagToMsgApi
  addFlagToMsgApi() async {
    FormData formData = FormData.fromMap({
      "user_id": loginData?.userId,
      "msg_id": messages.msgId,
      "notes": message.text,
    });

    final data = await APIFunction().apiCall(
      apiName: Constants.addFlagToMsg,
      params: formData,
      token: loginData?.token,
    );

    LoginDataModel model = LoginDataModel.fromJson(data);

    if (model.responseCode == 1) {
      Get.back();
      utils.showToast(message: model.responseMsg!);
    } else {
      utils.showSnackBar(message: model.responseMsg!, statusCode: model.responseCode);
    }
  }

  @override
  void onClose() {
    player.stop();
    if (!isClosed) {
      player.dispose();
    }
    super.onClose();
  }
}
