import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:hub/features/local/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_model.dart';

class LocalProfileEvent {}

class LocalProfileState {
  final String cliName;
  final String cliUUID;
  final String ownerName;

  LocalProfileState(
      {this.cliName = '', this.cliUUID = '', this.ownerName = ''});

  LocalProfileState copyWith(
      {String? cliName, String? ownerName, String? cliUUID}) {
    return LocalProfileState(
      cliName: cliName ?? this.cliName,
      ownerName: ownerName ?? this.ownerName,
      cliUUID: cliUUID ?? this.cliUUID,
    );
  }
}

class LocalProfileBloc extends Bloc<LocalProfileEvent, LocalProfileState> {
  late StreamSubscription<bool> _completer;

  LocalProfileBloc() : super(LocalProfileState()) {
    on<LocalProfileEvent>(_onLocalProfileEvent);
    _completer = LocalsRepositoryImpl.license.stream.listen((v) {
      add(LocalProfileEvent());
    });
  }

  @override
  Future<void> close() {
    _completer.cancel();
    return super.close();
  }

  Future<void> _onLocalProfileEvent(
      LocalProfileEvent event, Emitter<LocalProfileState> emit) async {
    final cliName =
        (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
    final ownerName =
        (await StorageHelper().get(ProfileStorageKey.ownerName.key)) ?? '';
    final cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    emit(state.copyWith(
        cliName: cliName, cliUUID: cliUUID, ownerName: ownerName));
  }

  // void updateProfile(BuildContext context) {
  //   LocalsRepositoryImpl.license.add(false);
  //   context.read<MenuBloc>().add(MenuEvent());
  //   add(LocalProfileEvent());
  //   LocalsRepositoryImpl.license.add(true);
  // }
}

class LocalProfileComponentModel
    extends FlutterFlowModel<LocalProfileComponentWidget> {
  String cliName = '';
  String cliUUID = '';
  String ownerName = '';
  VoidCallback? setStateCallback;

  @override
  void initState(BuildContext context) {
    getData();
  }

  Future<void> getData() async {
    cliName =
        (await StorageHelper().get(ProfileStorageKey.clientName.key)) ?? '';
    ownerName =
        (await StorageHelper().get(ProfileStorageKey.ownerName.key)) ?? '';
    cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
    setStateCallback?.call();
  }

  @override
  void dispose() {}
}
