// ignore_for_file: use_build_context_synchronously

import 'dart:async';
import 'dart:convert';
import 'dart:developer';

import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:sfm_app/product/services/api_services.dart';
import 'package:sfm_app/product/utils/device_utils.dart';

import '../device_model.dart';

import '../../../product/base/bloc/base_bloc.dart';

class DetailDeviceBloc extends BlocBase {
  APIServices apiServices = APIServices();

  final deviceInfo = StreamController<Device>.broadcast();
  StreamSink<Device> get sinkDeviceInfo => deviceInfo.sink;
  Stream<Device> get streamDeviceInfo => deviceInfo.stream;

  final deviceSensor = StreamController<Map<String, dynamic>>.broadcast();
  StreamSink<Map<String, dynamic>> get sinkDeviceSensor => deviceSensor.sink;
  Stream<Map<String, dynamic>> get streamDeviceSensor => deviceSensor.stream;

  final deviceLocation = StreamController<String>.broadcast();
  StreamSink<String> get sinkDeviceLocation => deviceLocation.sink;
  Stream<String> get streamDeviceLocation => deviceLocation.stream;

  @override
  void dispose() {}

  void getDeviceDetail(
    BuildContext context,
    String thingID,
    Completer<GoogleMapController> controller,
  ) async {
    String body = await apiServices.getDeviceInfomation(thingID);
    if (body != "") {
      final data = jsonDecode(body);
      Device device = Device.fromJson(data);
      sinkDeviceInfo.add(device);
      if (device.areaPath != null) {
        String fullLocation = await DeviceUtils.instance
            .getFullDeviceLocation(context, device.areaPath!);
        log("Location: $fullLocation");
        sinkDeviceLocation.add(fullLocation);
      }
      Map<String, dynamic> sensorMap = {};
      if (device.status!.sensors != null) {
        sensorMap = DeviceUtils.instance
            .getDeviceSensors(context, device.status!.sensors!);
      } else {
        sensorMap = DeviceUtils.instance.getDeviceSensors(context, []);
      }
      sinkDeviceSensor.add(sensorMap);
      if (device.settings!.latitude! != "" &&
          device.settings!.longitude! != "") {
        final CameraPosition cameraPosition = CameraPosition(
          target: LatLng(
            double.parse(device.settings!.latitude!),
            double.parse(device.settings!.longitude!),
          ),
          zoom: 13,
        );
        final GoogleMapController mapController = await controller.future;
        mapController
            .animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
      }
    }
  }

  void findLocation(BuildContext context, String areaPath) async {
    String fullLocation =
        await DeviceUtils.instance.getFullDeviceLocation(context, areaPath);
    sinkDeviceLocation.add(fullLocation);
  }
}
