import 'package:audio_service/audio_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import '../auth/auth_provider.dart';
import '../models/track.dart';
import 'audio_handler.dart';

final audioHandlerProvider = Provider<MinstrelAudioHandler>((ref) {
  throw UnimplementedError('overridden in main()');
});

final playbackStateProvider = StreamProvider<PlaybackState>(
  (ref) => ref.watch(audioHandlerProvider).playbackState,
);

final mediaItemProvider = StreamProvider<MediaItem?>(
  (ref) => ref.watch(audioHandlerProvider).mediaItem,
);

final queueProvider = StreamProvider<List<MediaItem>>(
  (ref) => ref.watch(audioHandlerProvider).queue,
);

class PlayerActions {
  PlayerActions(this._ref);
  final Ref _ref;

  Future<void> playTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
    final url   = await _ref.read(serverUrlProvider.future);
    final token = await _ref.read(secureStorageProvider).read(key: 'session_token');
    final h = _ref.read(audioHandlerProvider)..configure(baseUrl: url ?? '', token: token);
    await h.setQueueFromTracks(tracks, initialIndex: initialIndex);
    await h.play();
  }
}

final playerActionsProvider = Provider<PlayerActions>((ref) => PlayerActions(ref));
