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

class NewsListViewModel extends RestfulApiViewModel {
  String folderUri;
  final RxList<PageItemModel> newsList = <PageItemModel>[].obs;
  var _canLoadMore = true;
  final int _limit = 20;
  bool _websiteApiLoaded = false;
  bool get canLoadMore => _canLoadMore;

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

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

  Future<void> getNewsList({bool isRefresh = false}) async {
    if (isRefresh) _canLoadMore = true;
    if (!isRefresh && !_canLoadMore) return;
    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: isRefresh,
    );
  }
}
