import '../../../core/contracts/library.dart';
import 'cross_server_playlist.dart';
import 'playlist.dart';
import 'series_episode_playlist.dart';
import 'single_item_playlist.dart';

typedef LoadDetailFn = Future<MediaDetailRes> Function(String itemId);


Future<Playlist> playlistFromLaunch({
  required String itemId,
  String? mediaSourceId,
  int? startPositionTicks,
  int? preferredAudioStreamIndex,
  int? preferredSubtitleStreamIndex,
  bool playFromStart = false,
  List<CrossServerPlaylistEntry>? crossServerSequence,
  required LoadDetailFn loadDetail,
  required LoadEpisodesFn loadEpisodes,
  required LoadSeasonsFn loadSeasons,
}) async {
  if (crossServerSequence != null && crossServerSequence.isNotEmpty) {
    var initialIndex = crossServerSequence.indexWhere(
      (e) => e.itemId == itemId,
    );
    if (initialIndex < 0) initialIndex = 0;
    return CrossServerPlaylist(
      sequence: crossServerSequence,
      initialIndex: initialIndex,
      initialPlayFromStart: playFromStart,
    );
  }

  final detail = await loadDetail(itemId);
  final base = detail.base;
  if (base.Type == 'Episode' &&
      base.SeriesId != null &&
      base.SeasonId != null) {
    final seriesPlaylist = SeriesEpisodePlaylist(
      seriesId: base.SeriesId!,
      loadEpisodes: loadEpisodes,
      loadSeasons: loadSeasons,
    );
    await seriesPlaylist.initialize(
      seasonId: base.SeasonId!,
      episodeId: itemId,
      initialIndexNumber: base.IndexNumber,
      initialMediaSourceId: mediaSourceId,
      initialStartPositionTicks: startPositionTicks,
      initialPreferredAudioStreamIndex: preferredAudioStreamIndex,
      initialPreferredSubtitleStreamIndex: preferredSubtitleStreamIndex,
      initialPlayFromStart: playFromStart,
      preloadedItem: base,
    );
    return seriesPlaylist;
  }

  return SingleItemPlaylist(
    item: PlaylistItem(
      itemId: itemId,
      mediaSourceId: mediaSourceId,
      startPositionTicks: startPositionTicks,
      preferredAudioStreamIndex: preferredAudioStreamIndex,
      preferredSubtitleStreamIndex: preferredSubtitleStreamIndex,
      playFromStart: playFromStart,
      preloadedItem: base,
    ),
  );
}
