import 'package:equatable/equatable.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:image_picker/image_picker.dart';

part 'image_upload_state.dart';

class ImageUploadCubit extends Cubit<ImageUploadState> {
  ImageUploadCubit() : super(const ImageUploadState());

  void setStatus(ImageUploadStatus status) {
    emit(state.copyWith(status: status));
  }

  void setError(String? message) {
    emit(
      state.copyWith(status: ImageUploadStatus.failure, errorMessage: message),
    );
  }

  void addFiles(List<PlatformFile> files) {
    List<PlatformFile> newFiles = List.from(state.stagedFiles);
    newFiles.addAll(files);
    emit(
      state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
    );
  }

  void removeFile(PlatformFile file) {
    List<PlatformFile> newFiles = List.from(state.stagedFiles);
    newFiles.remove(file);
    emit(
      state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
    );
  }

  Future<void> addPhoto(XFile photo) async {
    final List<PlatformFile> files = List.from(state.stagedFiles);
    files.add(PlatformFile(name: photo.name, size: 0));
    emit(
      state.copyWith(
        status: ImageUploadStatus.addingPicture,
        stagedFiles: files,
      ),
    );
    final List<PlatformFile> newFiles = List.from(files);
    newFiles.removeLast();
    final PlatformFile loadedFile = PlatformFile(
      name: photo.name,
      size: await photo.length(),
      bytes: await photo.readAsBytes(),
      path: photo.path,
    );
    newFiles.add(loadedFile);

    emit(
      state.copyWith(status: ImageUploadStatus.success, stagedFiles: newFiles),
    );
  }
}
