import 'dart:convert';

import 'package:cashier_reserve/common/channel/model/call_status_change_model.dart';
import 'package:cashier_reserve/common/print/print.dart';
import 'package:flutter/services.dart';

import '../manager/event_manager.dart';
import 'model/call_log_model.dart';
import 'names.dart';

class MyEventChannel {
  static void startListener() {
    onGetCallLogResult();
    onCallStatusChange();
  }

  static void onGetCallLogResult() {
    EventChannel channel = EventChannel(getChannelName(kCallLogCallback));
    channel.receiveBroadcastStream().listen((Object? o) {
      GetCallLogEvent event = GetCallLogEvent();
      if (o is String) {
        event.isSuccess = true;
        List<dynamic> list = json.decode(o);
        List<CallLogModel> callLogs = [];
        for (var item in list) {
          callLogs.add(CallLogModel.fromJson(item));
          if (callLogs.length >= 100) {
            break;
          }
        }
        event.callLogs = callLogs.reversed.toList();
      } else {
        event.isSuccess = false;
      }
      EventManager.postEvent(event);
    }, onError: (Object error) {
      yjPrint("onGetCallLogResult error");
    });
  }

  static void onCallStatusChange() {
    EventChannel channel = EventChannel(getChannelName(kCallStatusChange));
    channel.receiveBroadcastStream().listen((Object? o) {
      yjPrint("onCallStatusChange: $o");
      if (o is String) {
        Map<String, dynamic> m = json.decode(o);
        CallStatusChangeModel model = CallStatusChangeModel.fromJson(m);
        EventManager.postEvent(CallStatusChangeEvent(model: model));
      }
    }, onError: (Object error) {
      yjPrint("onCallStatusChange error");
    });
  }
}