import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:nut_player/nut_player.dart';
import 'package:nut_player_example/src/features/main_screen/domain/firebase/firebase_provider.dart';
import 'package:nut_player_example/src/features/main_screen/domain/json_bloc/json_bloc.dart';
import 'package:nut_player_example/src/features/main_screen/domain/url_bloc/url_bloc.dart';

part 'main_event.dart';
part 'main_state.dart';

enum InputType { url, json }

class MainBloc extends Bloc<MainEvent, MainState> {

  MainBloc() : super(const ChosenJsonState()) {
    on<ChooseJsonEvent>(_onChooseJson);
    on<ChooseUrlEvent>(_onChooseUrl);
    on<OpenSettingsEvent>(_onOpenSettings);
    on<OpenPlayerEvent>(_onOpenPlayer);
  }

  _onChooseJson(ChooseJsonEvent event, Emitter<MainState> emit) {
    emit(const ChosenJsonState());
  }

  _onChooseUrl(ChooseUrlEvent event, Emitter<MainState> emit) {
    emit(const ChosenUrlState());
  }

  _onOpenSettings(OpenSettingsEvent event, Emitter<MainState> emit) {
    emit(SettingState(state.inputType));
  }

  _onOpenPlayer(OpenPlayerEvent event, Emitter<MainState> emit) {
    Provider? provider;

    final jsonUrlPath = event.jsonState.urlPath;
    final urlUrlPath = event.urlState.urlPath;

    if (event.jsonState.isFinal && jsonUrlPath != null) {
      if (event.jsonState is FirebaseChosenOptionState) {
        provider = FirebaseProvider(jsonUrlPath);
      } else if (event.jsonState is UseJsonOwnLinkState || event.jsonState is UseLinkExampleState) {
        provider = JsonProvider(jsonUrlPath);
      }
      // TODO: Поддежка Json-конфигов
    } else if (event.urlState.isFinal && urlUrlPath != null) {
      provider = CommonProvider.url(
          urlUrlPath,
          isLive: event.urlState.isLive ?? false,
          isLoop: event.isLoop
      );
    }

    if (provider != null) {
      emit(PlayerState(state.inputType, provider));
    }
  }
}
