from app_be.views.mongo_db import MongoManager
from django.http import JsonResponse
from app_be.services.hashservice import create_sha512


class MongoDBService:

    @staticmethod
    def check() -> bool:
        try:
            instance = MongoManager.getInstance()
            instance.AIC
        except:
            return False
        return True

    @staticmethod
    def getAll():
        instance = MongoManager.getInstance()

        db = instance.AIC
        col = db.metadata

        try:
            for resp in col.find():
                print(resp)
        except:
            print("Could not find Metadata")
        return resp

    @staticmethod
    def getSingle(identifier):

        instance = MongoManager.getInstance()

        db = instance.AIC
        col = db.metadata
        metadata = None
        try:
            resp = col.find({"identifier": identifier})
            metadata = resp[0]
        except:
            print("Could not find Metadata")
        if metadata is None:
            return None
        else:
            if '_id' in metadata:
                del metadata['_id']
        return metadata

    @staticmethod
    def createSingle(metadata, identifier, decoded_image):
        instance = MongoManager.getInstance()

        db = instance.AIC
        col = db.metadata

        try:
            metadata['identifier'] = identifier
            metadata['location'] = [metadata['longitude'], metadata['latitude']]
            metadata['sha512'] = create_sha512(decoded_image)
            col.insert_one(metadata)

        except:
            print("Could not insert Metadata")

    @staticmethod
    def deleteSingle(identifier):
        instance = MongoManager.getInstance()

        db = instance.AIC
        col = db.metadata

        try:
            resp = col.delete_one({"identifier": identifier})
            return resp
        except:
            print("Could not delete Metadata")
        return resp


    @staticmethod
    def deleteAll():
        instance = MongoManager.getInstance()

        db = instance.AIC
        col = db.metadata

        try:
            resp = col.delete_many({})
            return resp
        except:
            print("Could not delete Metadata")
        return resp