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

import 'package:sfm_app/feature/devices/device_model.dart';
import 'package:sfm_app/product/base/bloc/base_bloc.dart';
import 'package:sfm_app/product/services/api_services.dart';
import 'package:sfm_app/product/utils/date_time_utils.dart';

import '../../product/utils/device_utils.dart';
import 'device_logs_model.dart';

class DeviceLogsBloc extends BlocBase {
  APIServices apiServices = APIServices();
  final fromDate = StreamController<String>.broadcast();
  StreamSink<String> get sinkFromDate => fromDate.sink;
  Stream<String> get streamFromDate => fromDate.stream;

  final hasMore = StreamController<bool>.broadcast();
  StreamSink<bool> get sinkHasMore => hasMore.sink;
  Stream<bool> get streamHasMore => hasMore.stream;

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

  final sensors = StreamController<List<SensorLogs>>.broadcast();
  StreamSink<List<SensorLogs>> get sinkSensors => sensors.sink;
  Stream<List<SensorLogs>> get streamSensors => sensors.stream;

  @override
  void dispose() {}

  void getAllDevices() async {
    String body = await apiServices.getOwnerDevices();
    if (body != "") {
      final data = jsonDecode(body);
      List<dynamic> items = data['items'];
      List<Device> originalDevices = Device.fromJsonDynamicList(items);
      List<Device> devices =
          DeviceUtils.instance.sortDeviceByState(originalDevices);
      sinkAllDevices.add(devices);
    }
  }

  void getDeviceLogByThingID(
    int offset,
    String thingID,
    DateTime fromDate,
    List<SensorLogs> sensors,
  ) async {
    log("SensorLength: ${sensors.length}");
    String fromDateString =
        DateTimeUtils.instance.formatDateTimeToString(fromDate);
    String now = DateTimeUtils.instance.formatDateTimeToString(DateTime.now());
    // List<SensorLogs> sensors = [];
    Map<String, dynamic> params = {
      'thing_id': thingID,
      'from': fromDateString,
      'to': now,
      'limit': '30',
      "offset": offset.toString(),
      "asc": "true"
    };
    final body = await apiServices.getLogsOfDevice(thingID, params);
    if (body != "") {
      final data = jsonDecode(body);
      DeviceLog devicesListLog = DeviceLog.fromJson(data);
      if (devicesListLog.sensors!.isEmpty) {
        bool hasMore = false;
        sinkHasMore.add(hasMore);
      }
      if (devicesListLog.sensors!.isNotEmpty) {
        for (var sensor in devicesListLog.sensors!) {
          sensors.add(sensor);
        }
      }

      sinkSensors.add(sensors);
    }
  }
}
