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

import 'package:flutter/services.dart';

class FlutterJpushVip {
  static const MethodChannel _channel =
      const MethodChannel('flutter_jpush_vip');

  /// 初始化
  /// [production] ios only 生产环境
  static Future<_InitResult> init({bool production = true}) async {
    var map = await _channel.invokeMethod('init', {'production': production});
    return _InitResult.from(map);
  }

  ///
  /// iOS Only
  /// 申请推送权限,注意这个方法只会向用户弹出一次推送权限请求(如果用户不同意,之后只能用户到设置页面里面勾选相应权限),需要开发者选择合适的时机调用。
  ///
  void applyPushAuthority(
      [NotificationSettingsIOS iosSettings = const NotificationSettingsIOS()]) {
    if (!Platform.isIOS) {
      return;
    }
    _channel.invokeMethod('applyPushAuthority', iosSettings.toMap());
  }

  /// 开启调试模式
  static void debug() {
    _channel.invokeMethod('debug');
  }

  /// 获取注册ID
  static Future<String> getRegistrationID() {
    return _channel.invokeMethod('getRegistrationID');
  }

  /// 清除通知
  static void clearAllNotifications() {
    _channel.invokeMethod('clearAllNotifications');
  }

  /// 监听通知
  static void onNotification(Function(_Notification notification) callback) {
    _channel.setMethodCallHandler((call) {
      if (call.method == '__JPUSH_MESSAGE__') {
        try {
          Map map = call.arguments;
          if (call.arguments.runtimeType.toString().contains('String')) {
            map = json.decode(call.arguments);
          }
          var n = _Notification.from(map);
          callback(n);
        } catch (e) {
          print(e);
        }
      }
      return null;
    });
  }
}

class _InitResult {
  int code;
  String registrationId;

  _InitResult.from(Map map) {
    code = map['code'];
    registrationId = map['registrationId'];
  }
}

class _Notification {
  String msgId;
  String content;
  String title;
  Map extras;
  String platform;

  _Notification.from(Map map) {
    msgId = map['msg_id'].toString();
    content = map['n_content'];
    title = map['n_title'];
    extras = map['n_extras'];
    platform = map['rom_type'].toString();
  }

  @override
  String toString() {
    return 'Notification{msgId: $msgId, content: $content, title: $title, extras: $extras, platform: $platform}';
  }
}

class NotificationSettingsIOS {
  final bool sound;
  final bool alert;
  final bool badge;

  const NotificationSettingsIOS({
    this.sound = true,
    this.alert = true,
    this.badge = true,
  });

  Map<String, dynamic> toMap() {
    return <String, bool>{'sound': sound, 'alert': alert, 'badge': badge};
  }
}