import 'dart:io';

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

final log = Logger('firebaseHelper');

final FirebaseAuth auth = FirebaseAuth.instance;

Future<String> getToken() async {
  FirebaseUser firebaseUser = await auth.currentUser();
  IdTokenResult token = await firebaseUser.getIdToken();
  return token.token;
}

Future<Map> getClaims({bool refreshIdToken = false}) async {
  FirebaseUser firebaseUser = await auth.currentUser();
  if (firebaseUser == null) return null;
  IdTokenResult idToken =
      await firebaseUser.getIdToken(refresh: 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();
  }
  StorageReference storageReference =
      FirebaseStorage.instance.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++) {
    await deleteStorageFromUrl(urls[i]);
  }
}

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