import 'dart:io';

import 'package:firebase_auth/firebase_auth.dart' as fb;
import 'package:firebase_storage/firebase_storage.dart';
import 'package:logging/logging.dart';
import 'package:uuid/uuid.dart';

final log = Logger('firebaseHelper');

final fb.FirebaseAuth auth = fb.FirebaseAuth.instance;

Future<String> getToken() async {
  fb.User? firebaseUser = fb.FirebaseAuth.instance.currentUser;
  String token = await firebaseUser?.getIdToken() ?? "";
  return token;
}

Future<Map?> getClaims({bool refreshIdToken = false}) async {
  fb.User? firebaseUser = auth.currentUser;
  if (firebaseUser == null) return null;
  fb.IdTokenResult idToken =
      await firebaseUser.getIdTokenResult(refreshIdToken);
  return idToken.claims;
}

// returns list of url
Future<List<String>> uploadFiles(String path, List<File?> files,
    {String? fileName}) async {
  List<Future<String>> fu = [];
  for (File? f in files) {
    Future<String> u = uploadStorage(path, f);
    fu.add(u);
  }
  return Future.wait(fu);
}

Future<String> uploadStorage(String path, File? file,
    {String? fileName}) async {
  if (fileName == null) {
    fileName = Uuid().v4();
  }
  if (file == null) {
    return Future.value('');
  }
  Reference ref = FirebaseStorage.instance.ref().child('$path/$fileName');
  UploadTask uploadTask = ref.putFile(file);
  await uploadTask;
  String downloadUrl = await ref.getDownloadURL();
  return downloadUrl;
  // StorageReference storageReference =
  //     FirebaseStorage(storageBucket: Config.instance.bucketName)
  //         .ref()
  //         .child('$path/$fileName');
  // StorageUploadTask uploadTask = storageReference.putFile(file);
  // await uploadTask.onComplete;
  // String downloadUrl = await storageReference.getDownloadURL();
  // print("name:${await storageReference.getName()}");
  // print("bucket:${await storageReference.getBucket()}");
  // print("path:${await storageReference.getPath()}");
  // print("meta:${await storageReference.getMetadata()}");
  // return downloadUrl;
}

Future<void> deleteStorageFromUrls(List<String?> urls) async {
  if (urls == null) return;
  for (int i = 0; i < urls.length; i++) {
    if (urls[i] == null) return;
    await deleteStorageFromUrl(urls[i]!);
  }
}

Future<void> deleteStorageFromUrl(String url) async {
  try {
    Reference ref = FirebaseStorage.instance.refFromURL(url);
    await ref.delete();
    // StorageReference storageReference =
    //     await FirebaseStorage(storageBucket: Config.instance.bucketName)
    //         .getReferenceFromUrl(url);
    // await storageReference.delete();
  } catch (e) {
    log.warning("deleteStorage:$e");
  }
}
