import 'dart:async';
import 'dart:typed_data';

import 'package:flutter/cupertino.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_bloc.dart';
import 'package:hl_lieferservice/feature/authentication/bloc/auth_event.dart';
import 'package:hl_lieferservice/feature/authentication/exceptions.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_bloc.dart';
import 'package:hl_lieferservice/widget/operations/bloc/operation_event.dart';
import 'package:rxdart/rxdart.dart';

import '../../../../model/delivery.dart';
import 'note_event.dart';
import 'note_state.dart';
import 'package:hl_lieferservice/feature/delivery/detail/repository/note_repository.dart';

class NoteBloc extends Bloc<NoteEvent, NoteState> {
  final NoteRepository repository;
  final OperationBloc opBloc;
  final AuthBloc authBloc;
  final String deliveryId;

  StreamSubscription? _combinedSubscription;

  NoteBloc({
    required this.repository,
    required this.opBloc,
    required this.authBloc,
    required this.deliveryId,
  }) : super(NoteInitial()) {
    _combinedSubscription = CombineLatestStream.combine3(
          repository.notes,
          repository.images,
          repository.templates,
          (note, image, templates) {
            if (note == null || image == null || templates == null) {
              return null;
            }

            return {"note": note, "image": image, "templates": templates};
          },
        )
        .where((data) => data != null)
        .listen(
          (data) => add(
            DataUpdated(
              images: data!["image"] as List<ImageNote>,
              notes: data["note"] as List<Note>,
              templates: data["templates"] as List<NoteTemplate>,
            ),
          ),
        );

    on<LoadNote>(_load);
    on<AddNote>(_add);
    on<EditNote>(_edit);
    on<RemoveNote>(_remove);
    on<AddImageNote>(_upload);
    on<RemoveImageNote>(_removeImage);
    on<ResetNotes>(_reset);
    on<DataUpdated>(_dataUpdated);
  }

  @override
  Future<void> close() {
    _combinedSubscription?.cancel();
    return super.close();
  }

  void _handleError(Object e, String fallbackMessage) {
    if (e is UserUnauthorized) {
      authBloc.add(SessionExpiredEvent());
    } else {
      opBloc.add(FailOperation(message: fallbackMessage));
    }
  }

  Future<void> _dataUpdated(DataUpdated event, Emitter<NoteState> emit) async {
    emit(
      NoteLoaded(
        notes: event.notes,
        images: event.images,
        templates: event.templates,
      ),
    );
  }

  Future<void> _reset(ResetNotes event, Emitter<NoteState> emit) async {
    emit.call(NoteInitial());
  }

  Future<void> _removeImage(
    RemoveImageNote event,
    Emitter<NoteState> emit,
  ) async {
    opBloc.add(StartOperation());
    try {
      await repository.deleteImage(event.deliveryId, event.objectId);
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Löschen des Bildes: $e $st");
      _handleError(e, "Fehler beim Löschen des Bildes");
    }
  }

  Future<void> _upload(AddImageNote event, Emitter<NoteState> emit) async {
    opBloc.add(StartOperation());
    try {
      Uint8List imageBytes = await event.file.readAsBytes();
      await repository.addImage(event.deliveryId, imageBytes);
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen des Bildes: $e $st");
      _handleError(e, "Fehler beim Hinzufügen des Bildes");
    }
  }

  Future<void> _load(LoadNote event, Emitter<NoteState> emit) async {
    if (state is NoteLoaded || state is NoteLoading) {
      return;
    }

    emit.call(NoteLoading());

    try {
      await repository.loadNotes(event.delivery.id);
      await repository.loadTemplates();
    } catch (e, st) {
      debugPrint("Fehler beim Herunterladen der Notizen: $e $st");
      if (e is UserUnauthorized) {
        authBloc.add(SessionExpiredEvent());
        return;
      }
      opBloc.add(FailOperation(message: "Notizen konnten nicht heruntergeladen werden."));
      emit.call(NoteLoadingFailed());
    }
  }

  Future<void> _add(AddNote event, Emitter<NoteState> emit) async {
    opBloc.add(StartOperation());
    try {
      await repository.addNote(event.deliveryId, event.note);
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Hinzufügen der Notiz: $e $st");
      _handleError(e, "Fehler beim Hinzufügen der Notiz");
    }
  }

  Future<void> _edit(EditNote event, Emitter<NoteState> emit) async {
    opBloc.add(StartOperation());
    try {
      await repository.editNote(event.noteId, event.content);
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Editieren der Notiz: $e $st");
      _handleError(e, "Fehler beim Editieren der Notiz");
    }
  }

  Future<void> _remove(RemoveNote event, Emitter<NoteState> emit) async {
    opBloc.add(StartOperation());
    try {
      await repository.deleteNote(event.noteId);
      opBloc.add(FinishOperation());
    } catch (e, st) {
      debugPrint("Fehler beim Löschen der Notiz: $e $st");
      _handleError(e, "Notiz konnte nicht gelöscht werden");
    }
  }
}
