import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:flutter/foundation.dart';
import 'package:image_picker/image_picker.dart';
import 'package:just_audio/just_audio.dart';

class MediaService {
  static final AudioPlayer audioPlayer = AudioPlayer();
  static String? audioPlayerTag;
  static String? audioPlayerTitle;
  static String? audioPlayerCover;

  static void init() {
    audioPlayer.positionStream.listen((event) {
      if (audioPlayer.duration != null && audioPlayer.duration! < event) {
        audioPlayer.stop();
        audioPlayer.seek(const Duration(seconds: 0));
      }
    });
  }

  static Future<void> handleAudioPlayback({
    required dynamic audioSource,
  }) async {
    bool isNetworkAudio = audioSource.runtimeType == String;
    String tag;
    if (isNetworkAudio) {
      tag = audioSource;
    } else {
      tag = audioSource.path;
    }
    if (audioPlayerTag == tag) {
      if (audioPlayer.playing) {
        await audioPlayer.pause();
      } else {
        await audioPlayer.play();
      }
    } else {
      await audioPlayer.stop();
      audioPlayerTag = tag;
      if (isNetworkAudio) {
        await audioPlayer.setUrl(
          RequestHelper.baseUrl +
              audioSource +
              '?accessToken=${RequestService.token}',
        );
      } else {
        if (kIsWeb) {
          await audioPlayer
              .setUrl(audioSource!.uri.path.replaceAll('%3A', ':'));
        } else {
          await audioPlayer.setFilePath(audioSource.path);
        }
      }
      audioPlayer.play();
    }
  }

  static Future<void> resetAudioPlayer() async {
    audioPlayerTag = null;
    MediaService.audioPlayer.stop();
  }

  static Future<XFile?> pickImage({required ImageSource source}) async {
    final imagePicker = ImagePicker();
    final XFile? pickedFile = await imagePicker.pickImage(source: source);
    return pickedFile;
  }
}
