
import '../../api/apiResponse.dart';
import '../../api/marianumcloud/webdav/queries/listFiles/listFilesCache.dart';
import '../../api/marianumcloud/webdav/queries/listFiles/listFilesResponse.dart';
import '../dataHolder.dart';

extension ExtendedList on List {
  T indexOrNull<T>(int index) =>  index +1 <= length ? this[index] : null;
  T firstOrNull<T>() => isEmpty ? null : first;
  T lastOrNull<T>() => isEmpty ? null : last;
}

class FilesProps extends DataHolder {
  List<String> folderPath = List<String>.empty(growable: true);
  String currentFolderName = "Home";

  ListFilesResponse? _listFilesResponse;
  ListFilesResponse get listFilesResponse => _listFilesResponse!;

  void runPath(List<String> path) {
    folderPath = path;
    run();
  }

  @override
  List<ApiResponse?> properties() {
    return [_listFilesResponse];
  }

  @override
  void run() {
    _listFilesResponse = null;
    notifyListeners();
    ListFilesCache(
      path: folderPath.isEmpty ? "/" : folderPath.join("/"),
      onUpdate: (ListFilesResponse data) => {
        _listFilesResponse = data,
        notifyListeners(),
      }
    );
  }

  void enterFolder(String name) {
    folderPath.add(name);
    currentFolderName = name;
    run();
  }

  void popFolder() {
    folderPath.removeLast();
    if(folderPath.isEmpty) currentFolderName = "Home";
    run();
  }
}