import 'dart:async';
import 'dart:convert';
import 'package:amos_flutter_utils/amos_flutter_utils.dart';
import 'package:event_bus/event_bus.dart';

PubSub _ps;
EventBus _eb = EventBus();

class EventDataType {
  /// 警情数据
  static const String AlarmDisaster = 'AlarmDisaster';
  /// 编辑集结点数据
  static const String EditAssemblyPoint = 'editAssemblyPoint';
  /// 当前设备距离灾情的距离
  static const String Self2AlarmDistance = 'self2AlarmDistance';
  /// 当前设备距离集结点的距离
  static const String Self2AssemblyPointDistance = 'self2AssemblyPointDistance';
  /// 点击地图空白处
  static const String MapClickEmpty = 'mapClickEmpty';
  /// 定位
  static const String ChooseLocation = 'chooseLocation';
}

/// 事件数据，主要用于事件发送时进行分发
class EventData {
  EventData({this.type, this.content});

  /// 数据类型
  String type;

  /// 内容
  dynamic content;

  /// jsonEncode 方法中会调用实体类的这个方法。如果实体类中没有这个方法，会报错。
  Map toJson() {
    Map map = <String, dynamic>{};
    map['type'] = type;
    map['content'] = content;
    return map;
  }

  static EventData fromMap(Map<String, dynamic> map) {
    EventData jsonModel = EventData(type: map['type'], content: map['content']);
    return jsonModel;
  }

  /// 将json字符串转化成对象
  static EventData parseJson(String jsonStr) {
    EventData edModel = fromMap(jsonDecode(jsonStr));
    return edModel;
  }

  @override
  String toString() {
    return 'EventData: {type: $type, content: $content}';
  }
}

/// 指挥事件总线
class DispatchEvents {
  static PubSub getInstance() {
    _ps ??= PubSub(_eb);
    return _ps;
  }
  /// 订阅消息
  /// - [listener] 订阅消息执行方法
  /// - [tagName] 订阅消息的别名，不能同名
  static StreamSubscription on(Function listener, String tagName) {
    return getInstance().on(listener, tagName);
  }

  static void fire(event) {
    getInstance().fire(event);
  }

  static void off(event) {
    getInstance().fire(event);
  }

  /// 取消订阅
  static void cancel(dynamic tar) {
    getInstance().cancel(tar);
  }

  static void destroy() {
    getInstance().destroy();
  }
}

class DispatchTagNames {
  /// main map 主消息 tagName
  static const String MAIN_MAP = 'MAIN_MAP';
}