import 'dart:async';
import 'package:flutter/material.dart';
import 'package:aves/model/entry/entry.dart';
import 'package:aves/services/common/services.dart';

/// Gestione CAST.
/// Versione ultra‑ottimizzata, senza album, senza grouping, senza filter_grids.
/// Funziona con il tuo nuovo modello folder‑based + remote origin.
class EntryActionCast {
  final BuildContext context;
  final List<AvesEntry> entries;

  EntryActionCast(this.context, this.entries);

  // ------------------------------------------------------------
  // ENTRY POINT
  // ------------------------------------------------------------

  Future<void> startCast() async {
    if (entries.isEmpty) {
      _show('Nessun elemento da inviare al Cast');
      return;
    }

    try {
      final ok = await _connect();
      if (!ok) {
        _show('Nessun dispositivo Cast disponibile');
        return;
      }

      await _sendMedia(entries);
      _show('Invio al Cast in corso…');
    } catch (e) {
      _show('Errore Cast: $e');
    }
  }

  // ------------------------------------------------------------
  // CONNECTION
  // ------------------------------------------------------------

  Future<bool> _connect() async {
    try {
      final connected = await castService.connect();
      return connected;
    } catch (_) {
      return false;
    }
  }

  // ------------------------------------------------------------
  // SEND MEDIA
  // ------------------------------------------------------------

  Future<void> _sendMedia(List<AvesEntry> entries) async {
    for (final entry in entries) {
      await castService.sendMedia(
        uri: entry.uri,
        mimeType: entry.mimeType,
        title: entry.bestTitle,
      );
    }
  }

  // ------------------------------------------------------------
  // CONTROLS
  // ------------------------------------------------------------

  Future<void> next() async {
    try {
      await castService.next();
    } catch (e) {
      _show('Errore next: $e');
    }
  }

  Future<void> previous() async {
    try {
      await castService.previous();
    } catch (e) {
      _show('Errore previous: $e');
    }
  }

  Future<void> stop() async {
    try {
      await castService.stop();
      _show('Cast terminato');
    } catch (e) {
      _show('Errore stop: $e');
    }
  }

  // ------------------------------------------------------------
  // UTILS
  // ------------------------------------------------------------

  void _show(String msg) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(content: Text(msg)),
    );
  }
}
