"""
The Docker Container "database" needs to run to execute this tests properly
"""
import base64
import os
import unittest

from app import db
from Models import ImageModel
from Rest.ImagesREST import ImagesREST
from Models.UserModel import UserModel
from Rest.Answer import MessageCodes


def prepare_db():
    db.session.commit()
    db.drop_all()
    db.create_all()
    db.session.commit()


def setup_one():
    """
    One user with a set profile picture.
    """
    prepare_db()
    # create user
    user_one = UserModel.create("user_one", "somepassword123", "norealmail@mail.de")
    db.session.commit()
    # set pic
    script_dir = os.path.dirname(os.path.abspath(__file__))
    file_path = os.path.join(script_dir, '../../Images/avatar1.png')
    with open(file_path, "rb") as img_file:
        image_base64 = base64.b64encode(img_file.read())
        image = base64.b64decode(image_base64)
    profile_image = ImageModel(uploader=user_one, data=image)
    db.session.add(profile_image)
    db.session.commit()
    user_one.profile_pic = profile_image
    db.session.add(user_one)
    db.session.commit()

    return {"user_one": user_one, "image_one": profile_image}


class TestProjectRest(unittest.TestCase):

    def test_delete_own_profile_pic(self):
        # SETUP
        setup = setup_one()
        user_one = setup['user_one']
        image_one = setup['image_one']

        # ACTION
        delete_profile_pic_result = ImagesREST.delete_images(user_one.id, image_one.id)

        # RESULT
        # right message code
        self.assertTrue(MessageCodes.IMAGE_DELETE_SUCCESS.value, delete_profile_pic_result.message)
        # the image is not present anymore
        self.assertFalse(ImageModel.query.all())
        # the user has no image set
        self.assertFalse(user_one.profile_pic)
