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

        metadata_orig = MongoDBService.getSingle(identifier)
        metadata_new = metadata_orig
        metadata_new['previous'] = identifier + '_' + str(metadata_orig['version'])
        identifier_changed = identifier + '_' + str(metadata_orig['version'])  # Set identifier to include version
        metadata_new['version'] = str(int(metadata_new['version']) + 1)  # Increment version by one

        metadata_new.update(meta)

        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(metadata_new, 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
