import 'package:get/get.dart';
import 'package:mypoint_flutter_app/networking/api/website_api.dart' deferred as website_api;
import '../../networking/restful_api_viewmodel.dart';
import '../faqs/faqs_model.dart';

class NewsListViewModel extends RestfulApiViewModel {
  String folderUri;
  final RxList<PageItemModel> newsList = <PageItemModel>[].obs;
  final RxBool isLoading = false.obs;
  var _canLoadMore = true;
  int limit = 20;

  bool _websiteApiLoaded = false;

  Future<void> _ensureWebsiteApiLoaded() async {
    if (_websiteApiLoaded) return;
    await website_api.loadLibrary();
    _websiteApiLoaded = true;
  }

  NewsListViewModel({this.folderUri = "TIN-TUC"});

  @override
  onInit() {
    super.onInit();
    getNewsList();
  }

  Future<void> getNewsList({bool isRefresh = false}) async {
    if (isLoading.value) return;
    if (!isRefresh && !_canLoadMore) return;
    isLoading(true);
    final body = {"folder_uri": folderUri, "start": isRefresh ? 0 : newsList.length, "limit": limit};
    await callApi<FAQItemModelResponse>(
      request: () async {
        await _ensureWebsiteApiLoaded();
        final api = website_api.WebsiteApi(client);
        return api.websiteFolderGetPageList(body);
      },
      onSuccess: (data, _) {
        _canLoadMore = (data.items?.length ?? 0) == limit;
        if (isRefresh) {
          newsList.clear();
        }
        newsList.addAll(data.items ?? []);
      },
      withLoading: false,
      onComplete: () {
        isLoading(false);
      },
    );
  }
}