Untitled

 avatar
unknown
plain_text
a year ago
17 kB
4
Indexable
part of 'crush_feed_view.dart';

class CrushFeedViewCubit extends PaginatedListCubit<CrushFeedViewState, CrushFeedModel> {
  CrushFeedViewCubit(super.context, super.initialState);

  late final StumbleRepository _stumbleRepository = RepositoryProvider.of<StumbleRepository>(context);
  final TextEditingController messageController = TextEditingController();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  SwiperViewType? type;
  SwiperArgumentsData? swiperArgumentsData;
  int? replyId;
  int? parentCommentId;
  String? commentValue;

  @override
  void onCreate() {
    fetchList();
    listSubscription.addAll(
      [
        eventBus.listen((event) {
          _userUpdateEventBus(event);
        }),
        eventBus.listen(
          (event) async {
            if (event is BundleData) {
              _userIsPaidEvent(event);
            }
          },
        ),
      ],
    );
    getReportList();
    super.onCreate();
  }

  _userIsPaidEvent(BundleData event) async {
    User? user;
    if (pref.user?.isPaid == 0) {
      user = pref.user?.copyWith(isPaid: event.isPaid, redirectId: 4);
    }
    await UserCubit.of(context).updateUser(user ?? const User());
  }

  void _userUpdateEventBus(BusEvent event) {
    List<CrushFeedModel> crushFeedListUpdate = List<CrushFeedModel>.from(state.list);
    if (event.tag == AppEvent.updateComment) {
      var data = event.data as UpdateCommentAndLike;
      int index = state.list.indexWhere((item) {
        return item.id == data.postId;
      });
      crushFeedListUpdate[index] =
          crushFeedListUpdate[index].copyWith(id: data.postId, commentsCount: data.commentsCount);
      emit(state.copyWith(list: crushFeedListUpdate));
    } else if (event.tag == AppEvent.updateLike) {
      var data = event.data as UpdateCommentAndLike;
      int index = state.list.indexWhere((item) {
        return item.id == data.postId;
      });
      crushFeedListUpdate[index] =
          crushFeedListUpdate[index].copyWith(id: data.postId, likes: data.like, isLike: data.isLike);
      emit(state.copyWith(list: crushFeedListUpdate));
    }
  }

  @override
  Future<void> fetchList() async {
    Map<String, dynamic> map = {};

    var page = (state.list.length ~/ 10) + 1;
    map['page'] = page;

    if (state.searchController.text.isEmpty) {
      if (type == SwiperViewType.filter) {
        if (swiperArgumentsData?.answer1 != 0 && swiperArgumentsData?.question1 != 0) {
          map["question1"] = swiperArgumentsData?.question1.toString();
          map["answer1"] = swiperArgumentsData?.answer1.toString();
        }

        if (swiperArgumentsData?.question2 != "") {
          map["question2"] = swiperArgumentsData?.question2.toString();
        }

        if (swiperArgumentsData?.answer3 != 0 && swiperArgumentsData?.question3 != 0) {
          map["question3"] = swiperArgumentsData?.question3.toString();
          map["answer3"] = swiperArgumentsData?.answer3.toString();
        }

        if (swiperArgumentsData?.toAge != 18 || swiperArgumentsData?.fromAge != 100) {
          map["to_age"] = swiperArgumentsData?.toAge.toString();
          map["from_age"] = swiperArgumentsData?.fromAge.toString();
        }

        if (swiperArgumentsData?.toHeight != 1 || swiperArgumentsData?.fromHeight != 300) {
          map["to_height"] = swiperArgumentsData?.toHeight.toString();
          map["from_height"] = swiperArgumentsData?.fromHeight.toString();
        }

        if (swiperArgumentsData?.toWeight != 1 || swiperArgumentsData?.fromWeight != 300) {
          map["to_weight"] = swiperArgumentsData?.toWeight.toString();
          map["from_weight"] = swiperArgumentsData?.fromWeight.toString();
        }
      }
    } else {
      map['user_name'] = state.searchController.text;
    }
    getCrushFeedListView(map: map, page: page);
  }

  void getReportList({int? type}) {
    processData(
      _stumbleRepository.getReportList(type: 0),
      onLoading: (isLoading) => false,
      onSuccess: (data) {
        Log.debug("dararar - > ${jsonEncode(data)}");
        emit(state.copyWith(reportList: data));
      },
    );
  }

  @override
  Future<void> close() {
    pref.swiperArgData = const SwiperArgumentsData();
    return super.close();
  }

  getCrushFeedListView({required Map<String, dynamic> map, int? page}) {
    processData<List<CrushFeedModel>>(
      _stumbleRepository.getCrushFeedList(map: map),
      onLoading: (isLoading) => emit(state.copyWith(isLoading: isLoading)),
      onSuccess: (data) {
        emit(
          state.copyWith(
            list: page == 1 ? data : appendList(state.list, data),
            reachAtEnd: data.length < AppConst.PAGE_SIZE,
          ),
        );
      },
    );
  }

  void onShowWidget({bool? isShowWidget, String? fullName, int? connectionPostId, int? index}) {
    state.commentController.clear();
    emit(state.copyWith(
      isShowWidget: isShowWidget,
      fullName: fullName,
      connectionPostId: connectionPostId,
      index: index,
    ));
  }

  postCommentField({required int id, required int index}) async {
    commentValue = state.commentController.text;
    state.commentController.clear();
    var crushFeedList = List<CrushFeedModel>.from(state.list);
    crushFeedList[index] = crushFeedList[index].copyWith(commentsCount: crushFeedList[index].commentsCount + 1);
    emit(state.copyWith(list: crushFeedList, isShowWidget: false));

    processData<dynamic>(
      _stumbleRepository.postComment(
        id: id.toString(),
        comment: commentValue,
      ),
      handleLoading: false,
      onSuccess: (data) {
        context.navigator
            .pushNamed(CrushFeedDetailsView.routeName, arguments: commentWithType(id: id, type: "comment"));
        emit(state.copyWith(postCommentModel: PostCommentModel(), isShowWidget: false));
        eventBus.fire(
          BusEvent(
            AppEvent.updateComment,
            data: UpdateCommentAndLike(
              postId: id,
              commentsCount: state.list[index].commentsCount,
            ),
          ),
        );
      },
    );
  }

  void removeReply() {
    emit(state.copyWith(postCommentModel: PostCommentModel(), isShowWidget: false));
  }

  ///crush feed details navigation
  Future<void> crushFeedDetailsNavigation(int index) async {
    context.navigator
        .pushNamed(CrushFeedDetailsView.routeName, arguments: commentWithType(id: state.list[index].id))
        .then(
      (value) {
        if (value != null) {
          List<CrushFeedModel> crushData = List.from(state.list);

          var index = crushData.indexWhere((element) => element.id.toString() == value);

          if (index != -1) {
            crushData[index] = crushData[index].copyWith(isReport: true);
          }
          emit(state.copyWith(selectedReportIndex: 0, list: crushData));
        }
      },
    );
  }

  void goToSearchView(TextEditingController searchController) {
    emit(state.copyWith(list: []));
    Map<String, dynamic> map = {};
    map['user_name'] = searchController.text.trim();
    getCrushFeedListView(map: map);
  }

  goToFilter() {
    context.navigator.pushNamed(FilterView.routeName, arguments: FilterType.crushFeed).then((value) {
      if (value is SwiperArgumentsData) {
        swiperArgumentsData = value;
        type = SwiperViewType.filter;
        List<CrushFeedModel> list = List.from(state.list);
        list.clear();
        emit(state.copyWith(list: list));
        fetchList();
      }
    });
  }

  void likeAndUnLike(int index) {
    List<CrushFeedModel> list = List<CrushFeedModel>.from(state.list);
    list[index] = list[index].copyWith(isLike: !state[index].isLike);

    if (!state.list[index].isLike) {
      list[index] = list[index].copyWith(likes: state[index].likes + 1);
    } else {
      list[index] = list[index].copyWith(likes: state[index].likes - 1);
    }
    emit(state.copyWith(list: list));
    postLikeField(state.list[index].id, index);
  }

  postLikeField(int postId, int index) {
    processData<PostLikeModel>(
      _stumbleRepository.postLike(id: postId.toString()),
      handleLoading: false,
      onSuccess: (data) {},
    );
  }

  ///create chat
  Future<void> createChat(CrushFeedModel crushData) async {
    await UserCubit.of(context).createChat(
      toUserId: crushData.userId,
      convType: ConversationType.stumble.value,
    );
    if (context.mounted) {
      context.navigator.pushNamed(ChatView.routeName);
    }
  }

  void onCancel() {
    context.navigator.pop();
    messageController.clear();
  }

  void onSend(CrushFeedModel crushData) {
    if (formKey.currentState?.validate() ?? false) {
      processData<dynamic>(
        _stumbleRepository.sendChatRequest(
          id: crushData.id.toString(),
          message: messageController.text.trim(),
        ),
        onSuccess: (data) {
          List<CrushFeedModel> list = List.from(state.list);
          var index = list.indexWhere((element) => element.id == crushData.id);
          list[index] = list[index].copyWith(alreadyRequested: 1);
          emit(state.copyWith(list: list));
          context.navigator.pop();
          if (crushData.status == 1) {
            createChat(crushData);
          }
          messageController.clear();
        },
      );
    }
  }

  void showSendMessageDialog(CrushFeedModel crushData) {
    if (crushData.alreadyRequested == 0) {
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) {
          return Center(
            child: SingleChildScrollView(
              child: CommonOverlayImageDialog(
                title: context.l10n.labelSendMessageRequest,
                subTitleWidget: Form(
                  key: formKey,
                  child: Theme(
                    data: Theme.of(context).copyWith(
                      inputDecorationTheme: context.theme.inputDecorationTheme.copyWith(
                        fillColor: context.colorScheme.background,
                        filled: true,
                        hintStyle: context.theme.textTheme.titleSmall?.copyWith(
                          color: context.colorScheme.surfaceVariant,
                        ),
                      ),
                    ),
                    child: Padding(
                      padding: const EdgeInsets.symmetric(horizontal: 10.0),
                      child: TextFormField(
                        controller: messageController,
                        decoration: const InputDecoration(
                          hintText: "Write message",
                        ),
                        keyboardType: TextInputType.text,
                        textInputAction: TextInputAction.next,
                        style: const TextStyle(decoration: TextDecoration.none, fontSize: 20),
                        maxLines: 5,
                        validator: (value) => validateEmptyFields(value, msg: "Message"),
                      ),
                    ),
                  ),
                ),
                topWidget: const ImageFromAsset(
                  AppImages.icnIntimateRequest,
                ),
                positiveButton: ModalButton(onPressed: onCancel, label: context.l10n.btnCancel),
                negativeButton: ModalButton(
                  onPressed: () => onSend(crushData),
                  label: context.l10n.btnSend,
                ),
              ),
            ),
          );
        },
      );
    } else if (crushData.alreadyRequested == 1) {
      showErrorMessage(
        context: context,
        title: context.l10n.labelOops,
        content: context.l10n.errorYouHaveAllReadySendRequest,
      );
    } else {
      createChat(crushData);
    }
  }

  Future<void> onChat({required CrushFeedModel crushFeedModel}) async {
    if (pref.user?.isPaid == 0) {
      showPremiumDialog();
    } else {
      if (crushFeedModel.alreadyRequested == 0) {
        showSendMessageDialog(crushFeedModel);
      } else if (crushFeedModel.alreadyRequested == 1) {
        showErrorMessage(context: context, title: "Oops!", content: "Already sent Requested");
      } else {
        UserCubit.of(context).createUserChat(
          toUserId: crushFeedModel.userId,
          convType: ConversationType.stumble.value,
          onSuccess: (conversation) async {
            var inboxData =
                await database.getInboxData(pref.user?.id ?? 0, crushFeedModel.userId, ConversationType.stumble.value);
            if (context.mounted) {
              context.navigator.pushNamed(ChatView.routeName, arguments: inboxData);
            }
          },
        );
      }
    }
  }

  void showPremiumDialog() {
    showDialog(
      context: context,
      builder: (_) {
        return CommonPremiumDialog(
          positiveButton: () => context.navigator.popAndPushNamed(
            PremiumView.routeName,
            arguments:
                PremiumArgument(type: PremiumRedirectionType.crushFeed.value, redirectId: (pref.user?.redirectId ?? 0)),
          ),
        );
      },
    );
  }

  void onReport(int index) {
    showDialog(
      context: context,
      builder: (_) {
        return BlocProvider.value(
          value: this,
          child: Dialog(
            backgroundColor: context.colorScheme.surface,
            child: SingleChildScrollView(
              // padding: const EdgeInsets.all(16),
              child: Column(
                mainAxisSize: MainAxisSize.min,
                children: [
                  const Padding(
                    padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 20),
                    child: CommonText("Reason for Report", size: 18, fontWeight: FontWeight.w600),
                  ),
                  // const Gap(10),
                  const Divider(),
                  ...List.generate(
                    state.reportList.length,
                    (index) => BlocBuilder<CrushFeedViewCubit, CrushFeedViewState>(
                      builder: (context, state) {
                        return RadioListTile(
                          contentPadding: const EdgeInsets.only(left: 16, right: 16, top: 0, bottom: 0),
                          controlAffinity: ListTileControlAffinity.trailing,
                          value: index,
                          groupValue: state.selectedReportIndex,
                          onChanged: (value) {
                            emit(state.copyWith(selectedReportIndex: value));
                          },
                          title: Text(
                            state.reportList[index].title,
                            style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w500),
                          ),
                        );
                      },
                    ),
                  ),
                  Container(
                    width: context.width,
                    padding: const EdgeInsets.all(10),
                    child: PrimaryElevatedButton(
                      onTap: () {
                        context.navigator.pop();
                        onSubmitReport(index: state.selectedReportIndex, postId: state.list[index].id.toString());
                      },
                      label: "Report",
                      textGradiant: AppGradiant.whiteLightColor,
                    ),
                  )
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  onSubmitReport({String? postId = "", int index = 0}) async {
    List<ReportModel> tempList = List.from(state.reportList);
    final reportId = tempList[index].id;
    Log.debug("postId: ${postId}");
    await processData(
      _stumbleRepository.postSubmitReport(postId: postId ?? "", reportId: reportId.toString()),
      onSuccess: (data) {
        List<CrushFeedModel> crushData = List.from(state.list);
        var index = crushData.indexWhere((element) => element.id.toString() == postId);

        Log.debug("index :: $index");
        if (index != -1) {
          crushData[index] = crushData[index].copyWith(isReport: true);
        }

        showSuccessMessage(context: context, title: data['message'], content: '');
        emit(state.copyWith(selectedReportIndex: 0, list: crushData));
      },
    ).asFuture();
  }

  void onUndoPost(int postId) {
    processData(
      _stumbleRepository.undoPost(postId: postId),
      onSuccess: (data) {
        Log.debug("data :: $data");

        List<CrushFeedModel> crushData = List.from(state.list);

        var index = crushData.indexWhere((element) => element.id == postId);

        Log.debug("index :: $index");

        if (index != -1) {
          crushData[index] = crushData[index].copyWith(isReport: false);
        }

        emit(state.copyWith(list: crushData));
      },
    );
  }
}
Editor is loading...
Leave a Comment