import base64
from Models.ImageModel import ImageModel
from Rest.Answer import try_catch_error_answer, Answer, MessageCodes
from app import db


@try_catch_error_answer
class ImagesREST:
    @staticmethod
    def get_images(user, image_id):
        answer = Answer()
        image = ImageModel.query.get(image_id)
        # check if image exists
        if not image:
            return answer.add_message(MessageCodes.IMAGE_DOES_NOT_EXIST)
        else:
            return answer.add_image(image)

    @staticmethod
    def get_my_images(user):
        answer = Answer()
        images = ImageModel.query.filter(ImageModel.uploader == user)
        return answer.add_message(MessageCodes.WORKED).add_result(images)

    @staticmethod
    def delete_images(user, image_id):
        answer = Answer()
        image = ImageModel.query.get(image_id)
        # check if user is uploader
        if not image.uploader == user:
            return answer.add_message(MessageCodes.IMAGE_NOT_THE_UPLOADER)
        # check if image exists
        if not image:
            return answer.add_message(MessageCodes.IMAGE_DOES_NOT_EXIST)
        else:
            # check if image is profile pick
            if image == user.profile_pic:
                user.profile_pic = None
                db.session.add(user)
                db.session.commit()
            db.session.delete(image)
            db.session.commit()
            return answer.add_message(MessageCodes.IMAGE_DELETE_SUCCESS)

    @staticmethod
    def put_images(user, json_data):
        answer = Answer()

        image_data = base64.b64decode(json_data["image"])
        image = ImageModel(uploader=user, data=image_data)
        db.session.add(image)
        db.session.commit()
        return answer \
            .add_message(MessageCodes.IMAGE_UPLOAD_SUCCESS) \
            .add_result(image)
