import 'package:json_annotation/json_annotation.dart';

import '../../../../../view/pages/files/data/sort_options.dart';
import '../../../../api_response.dart';
import 'cacheable_file.dart';

part 'list_files_response.g.dart';

@JsonSerializable(explicitToJson: true)
class ListFilesResponse extends ApiResponse {
  Set<CacheableFile> files;

  ListFilesResponse(this.files);

  factory ListFilesResponse.fromJson(Map<String, dynamic> json) =>
      _$ListFilesResponseFromJson(json);
  Map<String, dynamic> toJson() => _$ListFilesResponseToJson(this);

  List<CacheableFile> sortBy({
    bool foldersToTop = true,
    SortOption sortOption = SortOption.name,
    bool reversed = false,
  }) {
    final ascending = SortOptions.getOption(sortOption).compare;
    // `reversed=true` means user picked "Aufsteigend" (a→z, oldest→newest,
    // smallest→largest); default is descending.
    final compare = reversed
        ? ascending
        : (CacheableFile a, CacheableFile b) => ascending(b, a);

    if (!foldersToTop) {
      return files.toList()..sort(compare);
    }

    final folders = files.where((f) => f.isDirectory).toList()..sort(compare);
    final regular = files.where((f) => !f.isDirectory).toList()..sort(compare);
    return [...folders, ...regular];
  }
}
