from datetime import datetime
import requests
from configs.firebase import  SERVER_TIMESTAMP, bucket, storage, db
import os
import tempfile
from werkzeug.utils import secure_filename
def get_file_path(filename):
    # Note: tempfile.gettempdir() points to an in-memory file system
    # on GCF. Thus, any files in it must fit in the instance's memory.
    file_name = secure_filename(filename)
    return os.path.join(tempfile.gettempdir(), file_name)


def upload_blob(source_file_name, destination_blob_name):
    """Uploads a file to the bucket."""
    # The ID of your GCS bucket
    # bucket_name = "your-bucket-name"
    # The path to your file to upload
    # source_file_name = "local/path/to/file"
    # The ID of your GCS object
    # destination_blob_name = "storage-object-name"

    blob = bucket.blob(destination_blob_name)

    blob.upload_from_filename(source_file_name)
    return str(blob.public_url)

def saveFile(
    uid,
    enterpriseId,
    fileName,
    source_file_name,
    private=False,
    type="misc"
):
    blob = bucket.blob(f"users/{type}/{source_file_name}")
    blob.upload_from_filename(source_file_name)
    url = blob.public_url
    file = dict(
        createdAt=datetime.now(),
        uid=uid,
        enterpriseId=enterpriseId,
        url=url,
        private=private,
        storageInfo = dict(
            publicUrl=url,
            bucketId = bucket.id,
            name=fileName,
        )
    )
    _, ref = db.collection("files").add(file)
    id =  ref.id
    ref.update(dict(id=id))
    file['id'] = id
    return file


def upload_from_file(file, destination_blob_name):
    blob = bucket.blob(destination_blob_name)
    blob.upload_from_file(file)
    blob.make_public()
    return str(blob.public_url)

def delete_blob(blob_name):
    try:
        """Deletes a blob from the bucket."""
        blob = bucket.blob(blob_name)
        blob.delete()
        print("Blob {} deleted.".format(blob_name))
        return True
    except Exception as e:
        print(e)
        return False


def list_blobs(bucket_name):
    """Lists all the blobs in the bucket."""
    # bucket_name = "your-bucket-name"

    storage_client = storage.Client()

    # Note: Client.list_blobs requires at least package version 1.17.0.
    blobs = storage_client.list_blobs(bucket_name)

    for blob in blobs:
        blob.make_public()
        
def downloadFile(fileName, url:str):
    res = requests.get(url)
    path = get_file_path(fileName)
    with open(path, 'wb') as f:
        f.write(res.content)
    return path