import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/studio_details_data.dart';
import 'package:didvan/providers/media.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';
import 'package:didvan/services/storage/storage.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 StudioDetailsData? currentPodcast;
  static StudioRequestArgs? podcastPlaylistArgs;

  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,
    required int id,
    bool? isNetworkAudio,
    bool isVoiceMessage = true,
  }) async {
    String tag;
    tag = '${isVoiceMessage ? 'message' : 'podcast'}-$id';
    isNetworkAudio ??= audioSource.runtimeType == String;
    if (!isVoiceMessage && MediaProvider.downloadedItemIds.contains(id)) {
      audioSource = StorageService.appDocsDir + '/podcasts/podcast-$id.mp3';
      isNetworkAudio = false;
    }
    if (audioPlayerTag == tag) {
      if (audioPlayer.playing) {
        await audioPlayer.pause();
      } else {
        await audioPlayer.play();
      }
    } else {
      await audioPlayer.stop();
      audioPlayerTag = tag;
      if (isNetworkAudio) {
        await audioPlayer.setUrl(
          isVoiceMessage
              ? (RequestHelper.baseUrl +
                  audioSource +
                  '?accessToken=${RequestService.token}')
              : audioSource,
        );
      } else {
        if (kIsWeb) {
          await audioPlayer.setUrl(audioSource!.replaceAll('%3A', ':'));
        } else {
          await audioPlayer.setFilePath(audioSource);
        }
      }
      audioPlayer.play();
    }
  }

  static Future<void> resetAudioPlayer() async {
    audioPlayerTag = null;
    currentPodcast = null;
    podcastPlaylistArgs = 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;
  }
}
