
import 'package:nextcloud/nextcloud.dart';

import '../../../../../model/endpointData.dart';
import '../../webdavApi.dart';
import 'cacheableFile.dart';
import 'listFilesParams.dart';
import 'listFilesResponse.dart';

class ListFiles extends WebdavApi<ListFilesParams> {
  ListFilesParams params;

  ListFiles(this.params) : super(params);

  @override
  Future<ListFilesResponse> run() async {
    List<WebDavFile> davFiles = (await (await WebdavApi.webdav).propfind(PathUri.parse(params.path))).toWebDavFiles();
    Set<CacheableFile> files = davFiles.map((e) => CacheableFile.fromDavFile(e)).toSet();

    // webdav handles subdirectories wrong, this is a fix
    if(EndpointData().getEndpointMode() == EndpointMode.stage) {
      files = files.map((e) { // somehow
        e.path = e.path.split("mobile/cloud/remote.php/webdav")[1];
        return e;
      }).toSet();
    }

    // somehow the current working folder is also listed, it is filtered here.
    files.removeWhere((element) => element.path == "/${params.path}/" || element.path == "/");

    return ListFilesResponse(files);
  }
}