import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';

import '../api/jwt_token.dart';

class UserState extends Equatable {
  final String serialNumber;
  final Map<String, dynamic> user;
  final Map<String, dynamic> profile;
  final bool reset;
  final bool dnd;
  final bool servantDisplay;
  final bool houseKeeping;
  final String text;

  const UserState({
    this.serialNumber = '',
    this.user = const {},
    this.profile = const {},
    this.reset = false,
    this.dnd = false,
    this.servantDisplay = false,
    this.houseKeeping = false,
    this.text = '',
  });

  UserState copyWith({
    String? serialNumber,
    Map<String, dynamic>? user,
    Map<String, dynamic>? profile,
    bool? reset,
    bool? dnd,
    bool? servantDisplay,
    bool? houseKeeping,
    String? text,
  }) {
    return UserState(
      serialNumber: serialNumber ?? this.serialNumber,
      user: user ?? this.user,
      profile: profile ?? this.profile,
      reset: reset ?? this.reset,
      dnd: dnd ?? this.dnd,
      servantDisplay: servantDisplay ?? this.servantDisplay,
      houseKeeping: houseKeeping ?? this.houseKeeping,
      text: text ?? this.text,
    );
  }

  @override
  List<Object?> get props => [serialNumber, user, profile, reset, dnd, servantDisplay, houseKeeping, text];
}

class UserCubit extends Cubit<UserState> {
  UserCubit() : super(const UserState());
  final JwtToken token = JwtToken();

  void setSerialNumber(String value) {
    emit(state.copyWith(serialNumber: value));
  }

  void setUser(Map<String, dynamic> value) {
    emit(state.copyWith(user: value));
  }

  void setProfile(Map<String, dynamic> value) {
    emit(state.copyWith(profile: value));
  }

  void setReset(bool value) {
    emit(state.copyWith(reset: value));
  }

  void setDnd(bool value) {
    emit(state.copyWith(dnd: value));
  }

  void setServantDisplay(bool value) {
    emit(state.copyWith(servantDisplay: value));
  }

  void setHouseKeeping(bool value) {
    emit(state.copyWith(houseKeeping: value));
  }

  void setText(String value) {
    emit(state.copyWith(text: value));
  }

  void getUser() async {
    try {
      var res = await token.getUserData();
      if (res != null) {
        setUser(res);
      } else {
        setReset(true);
      }
    } catch (e) {
      setReset(true);
    }
  }
}
