import 'package:didvan/models/enums.dart';
import 'package:didvan/models/requests/studio.dart';
import 'package:didvan/models/srudio_data.dart';
import 'package:didvan/providers/core_provider.dart';
import 'package:didvan/services/network/request.dart';
import 'package:didvan/services/network/request_helper.dart';

class StudioState extends CoreProvier {
  final List<StudioData> studios = [];

  String? search;
  String? lastSearch;
  int page = 1;
  int lastPage = 1;

  int selectedSortTypeIndex = 0;

  bool _videosSelected = true;

  bool get videosSelected => _videosSelected;

  set videosSelected(bool value) {
    if (_videosSelected == value) return;
    _videosSelected = value;
    getStudioOverviews(page: page);
  }

  void init() {
    search = '';
    lastSearch = '';
    videosSelected = true;
    selectedSortTypeIndex = 0;
    Future.delayed(Duration.zero, () {
      getStudioOverviews(page: 1);
    });
  }

  String get _order {
    if (selectedSortTypeIndex == 0) return 'date';
    if (selectedSortTypeIndex == 1) return 'view';
    return 'comment';
  }

  Future<void> getStudioOverviews({required int page}) async {
    this.page = page;
    if (page == 1) {
      appState = AppState.busy;
    }

    final service = RequestService(
      RequestHelper.studioOverviews(
        args: StudioRequestArgs(
          page: page,
          type: videosSelected ? 'video' : 'podcast',
          search: search,
          order: _order,
        ),
      ),
    );

    await service.httpGet();
    if (service.isSuccess) {
      lastPage = service.result['lastPage'];
      final studioItems = service.result['studios'];
      for (var i = 0; i < studioItems.length; i++) {
        studios.add(StudioData.fromJson(studioItems[i]));
      }
      appState = AppState.idle;
      return;
    }
    appState = AppState.failed;
  }
}
