// ignore_for_file: use_build_context_synchronously

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import '../../product/services/map_services.dart';
import '../../product/shared/shared_snack_bar.dart';
import '../devices/device_model.dart';
import '../../product/base/bloc/base_bloc.dart';
import '../../product/services/api_services.dart';

class MapBloc extends BlocBase {
  APIServices apiServices = APIServices();
  MapServices mapServices = MapServices();
  @override
  void dispose() {}

  final mapType = StreamController<MapType>.broadcast();
  StreamSink<MapType> get sinkMapType => mapType.sink;
  Stream<MapType> get streamMapType => mapType.stream;

  final mapController = StreamController<GoogleMapController>.broadcast();
  StreamSink<GoogleMapController> get sinkmapController => mapController.sink;
  Stream<GoogleMapController> get streammapController => mapController.stream;

  final allDevices = StreamController<List<Device>>.broadcast();
  StreamSink<List<Device>> get sinkAllDevices => allDevices.sink;
  Stream<List<Device>> get streamAllDevices => allDevices.stream;

  final allMarker = StreamController<Set<Marker>>.broadcast();
  StreamSink<Set<Marker>> get sinkAllMarker => allMarker.sink;
  Stream<Set<Marker>> get streamAllMarker => allMarker.stream;

  final polylines = StreamController<List<LatLng>>.broadcast();
  StreamSink<List<LatLng>> get sinkPolylines => polylines.sink;
  Stream<List<LatLng>> get streamPolylines => polylines.stream;

  Future<void> updateCameraPosition(
    Completer<GoogleMapController> controller,
    double latitude,
    double longitude,
    double zoom,
  ) async {
    final CameraPosition cameraPosition =
        CameraPosition(target: LatLng(latitude, longitude), zoom: zoom);
    final GoogleMapController mapController = await controller.future;
    mapController.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
  }

  Future<void> findTheWay(
    BuildContext context,
    Completer<GoogleMapController> controller,
    LatLng origin,
    LatLng destination,
  ) async {
    List<LatLng> polylines = [];
    final polylineCoordinates =
        await mapServices.findTheWay(origin, destination);
    if (polylineCoordinates.isNotEmpty) {
      polylines = polylineCoordinates;
      sinkPolylines.add(polylines);
      await updateCameraPosition(
        controller,
        destination.latitude,
        destination.longitude,
        13.0,
      );
    } else {
      showNoIconTopSnackBar(
          context, "Không tìm thấy đường", Colors.orange, Colors.white);
    }
  }

  
}
