import 'package:bloc/bloc.dart';
import 'package:dio/dio.dart';
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:hoshan/data/model/forum_model.dart';
import 'package:hoshan/data/model/sort_by_model.dart';
import 'package:hoshan/data/repository/forum_repository.dart';

part 'comments_state.dart';

class CommentsCubit extends Cubit<CommentsState> {
  CommentsCubit() : super(CommentsInitial());

  static int page = 1;
  static int categoriesId = 1;
  static SortByModel sortByModel = SortByModel(text: 'جدیدترین', value: 'date');
  static int? lastPage;
  static final List<Comment> comments = [];

  void loadComments(
      {required final int cId,
      final bool retry = false,
      final SortByModel? orderBy}) async {
    if (cId != categoriesId || retry) {
      emit(CommentsInitial());
      page = 1;
      lastPage = null;
      categoriesId = cId;
      comments.clear();
    } else if (lastPage != null && page > lastPage!) {
      return;
    } else if (page != 1) {
      emit(CommentsLoading(comments: comments));
    }

    try {
      if (orderBy != null) sortByModel = orderBy;

      final cModel = await ForumRepository.getForumComments(
          categoryId: categoriesId, page: page, orderBy: sortByModel.value);

      page++;
      lastPage = cModel.lastPage;
      comments.addAll(cModel.comments!);

      emit(CommentsSuccess(comments: comments));
    } on DioException catch (e) {
      emit(CommentsFail());
      if (kDebugMode) {
        print("Dio Error is : $e");
      }
    }
  }

  void addComment({required final Comment comment}) {
    emit(CommentsLoading(comments: comments));
    comments.insert(0, comment);
    emit(CommentsSuccess(comments: comments));
  }

  void changeComment({
    required final Comment newComment,
  }) {
    emit(CommentsLoading(comments: comments));
    final index = comments.indexWhere(
      (element) => element.id == newComment.id,
    );
    comments[index] = newComment;
    emit(CommentsSuccess(comments: comments));
  }

  void addReplies({required final int commentId}) {
    emit(CommentsLoading(comments: comments));
    final comment = comments.firstWhere(
      (element) => element.id == commentId,
    );
    final index = comments.indexOf(comment);
    if (comment.replies == null) {
      comment.replies = 1;
    } else {
      comment.replies = comment.replies! + 1;
    }
    comments[index] = comment;
    emit(CommentsSuccess(comments: comments));
  }
}
