import json
import os
from io import BytesIO
from unittest import mock

import pytest
from django.contrib.auth.models import User
from django.core.files import File

from petale.models import CUT, AccessControlList, Partner, Petal
from petale.utils import etag

pytestmark = pytest.mark.django_db


def get_tests_file(filename):
    return os.path.join(os.path.dirname(__file__), 'data', filename)


def get_tests_file_content(filename):
    with open(get_tests_file(filename), 'rb') as fd:
        return fd.read()


def create_service(name, password=None):
    if not password:
        password = name
    user = User.objects.create(username=name)
    user.set_password(password)
    user.save()
    return user


def get_service(name):
    return User.objects.get(username=name)


def create_partner(name, admins=None, hg=2, sg=1, hk=1, sk=1):
    if not admins:
        admins = 'e.cartman@southpark.com,t.blakc@southpark.com'
    return Partner.objects.create(
        name=name,
        admin_emails=admins,
        hard_global_max_size=hg,
        soft_global_max_size=sg,
        hard_per_key_max_size=hk,
        soft_per_key_max_size=sk,
    )


def create_acl_record(order, partner, user, key, methods='*'):
    return AccessControlList.objects.create(order=order, partner=partner, user=user, key=key, methods=methods)


def create_petal(cut_uuid, partner, name, data, content_type):
    cut, created = CUT.objects.get_or_create(uuid=cut_uuid)
    return Petal.objects.create(
        cut=cut,
        partner=partner,
        name=name,
        size=len(data),
        etag=etag(data),
        data=File(BytesIO(data), name),
        content_type=content_type,
    )


class FakedResponse(mock.Mock):
    def json(self):
        return json.loads(self.content)


def create_cut(cut_uuid):
    cut, created = CUT.objects.get_or_create(uuid=cut_uuid)
    return cut
