import 'credentials_intf.dart';

class Profile {
  final ICredentials credentials;
  final String username;
  final String userId;
  final String avatar;
  final String serverName;
  final bool loggedIn;

  String get handle => '$username@$serverName';

  String get id => '${credentials.runtimeType.toString()}-$userId-$serverName';

  Profile({
    required this.credentials,
    required this.username,
    required this.userId,
    required this.avatar,
    required this.serverName,
    required this.loggedIn,
  });

  factory Profile.credentialsOnly(ICredentials credentials) => Profile(
        credentials: credentials,
        username: '',
        userId: '',
        avatar: '',
        serverName: credentials.serverName,
        loggedIn: false,
      );

  factory Profile.fromJson(
    Map<String, dynamic> json,
    ICredentials Function(Map<String, dynamic> json) credentialsFromJson,
  ) {
    final credentials = credentialsFromJson(json['credentials']);
    return Profile(
      credentials: credentials,
      username: json['username'],
      userId: json['userId'],
      avatar: json['avatar'],
      serverName: json['serverName'],
      loggedIn: json['loggedIn'],
    );
  }

  Profile copyWithLoginUpdate(bool status) => Profile(
        credentials: credentials,
        username: username,
        userId: userId,
        avatar: avatar,
        serverName: serverName,
        loggedIn: status,
      );

  Map<String, dynamic> toJson() => {
        'credentials': credentials.toJson(),
        'username': username,
        'userId': userId,
        'avatar': avatar,
        'serverName': serverName,
        'loggedIn': loggedIn,
      };

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is Profile && runtimeType == other.runtimeType && id == other.id;

  @override
  int get hashCode => id.hashCode;

  @override
  String toString() {
    return 'Profile{logged_in: $loggedIn, handle: $handle, credentials_id: $id}';
  }
}
