import 'dart:math';

import 'package:event_bus/event_bus.dart';
import 'package:flutter/cupertino.dart';
import 'package:naim/classes/assets.dart';
import 'package:naim/classes/message.dart';
import 'package:web_socket_channel/web_socket_channel.dart';

import 'Authenticate.dart';

const ASCII_START = 33;
const ASCII_END = 126;

//aphriapu_wp87
class AppData {
  static final AppData _appData = new AppData._internal();

  Map currentchat = {};
  Map<String, dynamic> dbUser = {};
  List<MainMessage> mainMsg = [];
  String passKey = "";
  BuildContext? context;
  bool newmessage = false;
  List<NAGroups> groups = [];
  WebSocketChannel? channel;
  String strPwd = "bhuyu6876547688";
  String constat = "closed";
  List<MessageKey> msgKeys = [];
  bool isHomeSet = false;
  EventBus? eventBus;
  List<NAUsers> contacts = [];
  factory AppData() {
    return _appData;
  }
  AppData._internal();

  NAUsers? getUserfrId(int userId) {
    if (contacts.isEmpty) {
      return null;
    }
    try {
      var gp = contacts.firstWhere((element) => element.id == userId);
      return gp;
    } catch (es) {}
    return null;
  }

  NAGroups? getGroupfrId(int grpId) {
    if (groups.isEmpty) {
      return null;
    }
    try {
      var gp = groups.firstWhere((element) => element.id == grpId);
      return gp;
    } catch (es) {}
    return null;
  }
}

final appData = AppData();

class SocketMessageEvent {
  dynamic data;

  SocketMessageEvent(this.data);
}

class HexColor extends Color {
  HexColor(final String hexColor) : super(_getColorFromHex(hexColor));

  static int _getColorFromHex(String hexColor) {
    hexColor = hexColor.toUpperCase().replaceAll('#', '');
    if (hexColor.length == 6) {
      hexColor = 'FF' + hexColor;
    }
    return int.parse(hexColor, radix: 16);
  }
}

final _internal = Random();

abstract class AbstractRandomProvider {
  double nextDouble();
}

class DefaultRandomProvider with AbstractRandomProvider {
  const DefaultRandomProvider();

  @override
  double nextDouble() => _internal.nextDouble();
}

class CoreRandomProvider with AbstractRandomProvider {
  Random random;

  CoreRandomProvider.from(this.random);

  @override
  double nextDouble() => random.nextDouble();
}

/// Generates a random integer where [from] <= [to].
int randomBetween(int from, int to,
    {AbstractRandomProvider provider = const DefaultRandomProvider()}) {
  if (from > to) throw Exception('$from cannot be > $to');
  var randomDouble = provider.nextDouble();
  if (randomDouble < 0) randomDouble *= -1;
  if (randomDouble > 1) randomDouble = 1 / randomDouble;
  return ((to - from) * provider.nextDouble()).toInt() + from;
}

String randomString(int length,
    {int from = ASCII_START,
    int to = ASCII_END,
    AbstractRandomProvider provider = const DefaultRandomProvider()}) {
  return String.fromCharCodes(List.generate(
      length, (index) => randomBetween(from, to, provider: provider)));
}
