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

import 'device_model.dart';
import '../../product/base/bloc/base_bloc.dart';
import '../../product/services/api_services.dart';

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

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

  final userRole = StreamController<String>.broadcast();
  StreamSink<String> get sinkUserRole => userRole.sink;
  Stream<String> get streamUserRole => userRole.stream;

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

  @override
  void dispose() {}

  void getDevice() 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);
    }
  }
}
