import 'package:flutter/material.dart';
import 'package:hub/features/backend/index.dart';
import 'package:hub/features/storage/index.dart';
import 'package:hub/flutter_flow/flutter_flow_model.dart';
import 'package:hub/flutter_flow/request_manager.dart';
import 'package:hub/pages/liberation_history/liberation_history_widget.dart';

class LiberationHistoryModel extends FlutterFlowModel<LiberationHistoryWidget> {
  late final String devUUID;
  late final String userUUID;
  late final String cliUUID;

  final unfocusNode = FocusNode();
  FocusNode? textFieldFocusNode;
  TextEditingController? textController;
  String? Function(BuildContext, String?)? textControllerValidator;

  final _getLiberationsManager = StreamRequestManager<ApiCallResponse>();
  Stream<ApiCallResponse> getLiberations({
    String? uniqueQueryKey,
    bool? overrideCache,
    required Stream<ApiCallResponse> Function() requestFn,
  }) =>
      _getLiberationsManager.performRequest(
        uniqueQueryKey: uniqueQueryKey,
        overrideCache: overrideCache,
        requestFn: requestFn,
      );
  void clearGetLiberationsCache() => _getLiberationsManager.clear();
  void clearGetLiberationsCacheKey(String? uniqueKey) =>
      _getLiberationsManager.clearRequest(uniqueKey);

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

  Future<void> init() async {
    devUUID = (await StorageHelper().get(ProfileStorageKey.devUUID.key)) ?? '';
    userUUID =
        (await StorageHelper().get(ProfileStorageKey.userUUID.key)) ?? '';
    cliUUID =
        (await StorageHelper().get(ProfileStorageKey.clientUUID.key)) ?? '';
  }

  Future answersRequest(
      {required BuildContext context,
      required String? ref,
      required String? task,
      required String? response,
      required String? id}) async {
    final ApiCallResponse? respondeSolicitacaoCall;
    final RespondeSolicitacaoCall callback = PhpGroup.respondeSolicitacaoCall;

    respondeSolicitacaoCall = await callback.call(
      referencia: ref,
      tarefa: task,
      resposta: response,
      idVisitante: id,
    );

    if (respondeSolicitacaoCall.statusCode == 200) {
      return !respondeSolicitacaoCall.jsonBody['error'];
    } else {
      return false;
    }
  }

  @override
  void dispose() {
    unfocusNode.dispose();
    textFieldFocusNode?.dispose();
    textController?.dispose();

    clearGetLiberationsCache();
  }
}
