from app_be.views.mongo_db import MongoManager
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
        resp = []

        try:
            for meta in col.find():
                meta['id'] = str(meta['_id'])
                del meta['_id']
                resp.append(meta)
        except:
            print("Could not find Metadata")

        return resp

    @staticmethod
    def getSingle(identifier):
        metadata = None
        try:
            instance = MongoManager.getInstance()

            db = instance.AIC
            col = db.metadata
            metadata = None
            resp = col.find({"identifier": identifier})
            metadata = resp[0]
            print("MongoDBService: Metadata: ", metadata)
        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

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

    @staticmethod
    def updateSingle(identifier, decoded_image, meta=None) -> bool:
        print("MongoDBService: Trying to update file with identifier " + identifier)
        instance = MongoManager.getInstance()
        db = instance.AIC
        col = db.metadata

        old = {"identifier": identifier}  # Query for old version

        existing_meta_data_copy = MongoDBService.getSingle(identifier)
        id_for_previous = identifier + '_' + str(meta['version'])
        existing_meta_data_copy['previous'] = id_for_previous
        identifier_changed = id_for_previous  # Set identifier to include version

        del meta['filename']
        existing_meta_data_copy.update(meta)

        existing_meta_data_copy['version'] = meta['version'] + 1  # Increment version by one

        print("MongoDBService: identifier_changed: ", identifier_changed)
        col.update_one(old, {"$set": {"identifier": identifier_changed, "filename": identifier_changed + '.jpg'}})

        print("MongoDBService: Old object is ", col.find_one({"identifier": identifier_changed}))

        MongoDBService.createSingle(existing_meta_data_copy, identifier, decoded_image)
        print("MongoDBService: New object is ", col.find_one({"identifier": identifier}))

        return True

    @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 replaceHash(identifier, decoded_image):
        instance = MongoManager.getInstance()
        db = instance.AIC
        col = db.metadata
        col.update_one({"identifier": identifier}, {"$set": {"sha512": create_sha512(decoded_image)}})

    @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
