import re

import pytest
from django.urls import reverse

from rdmo.views.models import View

from ..models import Project

users = (
    ('owner', 'owner'),
    ('manager', 'manager'),
    ('author', 'author'),
    ('guest', 'guest'),
    ('user', 'user'),
    ('site', 'site'),
    ('anonymous', None),
)

view_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'author': [1, 3, 5, 8],
    'guest': [1, 3, 5, 9],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

change_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

delete_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

export_project_permission_map = {
    'owner': [1, 2, 3, 4, 5],
    'manager': [1, 3, 5, 7],
    'api': [1, 2, 3, 4, 5],
    'site': [1, 2, 3, 4, 5, 6, 7, 8, 9]
}

projects = [1, 2, 3, 4, 5, 6, 7, 8, 9]

export_formats = ('rtf', 'odt', 'docx', 'html', 'markdown', 'tex', 'pdf')

site_id = 1
parent_project_id = 1
catalog_id = 1


@pytest.mark.parametrize('username,password', users)
def test_list(db, client, username, password):
    client.login(username=username, password=password)

    url = reverse('projects')
    response = client.get(url)

    projects = re.findall(r'/projects/(\d+)/', response.content.decode())

    if password:
        assert response.status_code == 200

        if username == 'site':
            assert projects == []
        else:
            assert sorted(list(set([int(project_id) for project_id in projects]))) \
                == view_project_permission_map.get(username, [])
    else:
        assert response.status_code == 302


@pytest.mark.parametrize('username,password', users)
def test_site(db, client, username, password):
    client.login(username=username, password=password)

    url = reverse('site_projects')
    response = client.get(url)

    projects = re.findall(r'/projects/(\d+)/update/', response.content.decode())