import pytest
from lxml import etree as ET

from yandex.maps.wiki.tasks import states
from yandex.maps.wiki.tasks import grinder
from yandex.maps.wiki.tasks import TASKS_NAMESPACE

NAMESPACES = {'ns': TASKS_NAMESPACE}

TASK_NAME = 'export'

TEST_UID = 1
TEST_BRANCH_ID = 2
TEST_COMMIT_ID = 1
TEST_TASK_ID = 1


def check_context(root):
    branch_element = root.find("./ns:task/ns:context/ns:export-context/ns:branch", NAMESPACES)
    assert branch_element.text == str(TEST_BRANCH_ID)


@pytest.mark.usefixtures('setup_acl_groups')
@pytest.mark.usefixtures('setup_permissions')
@pytest.mark.usefixtures('clean_schema')
@pytest.mark.parametrize('module_name', [TASK_NAME])
def test_export(client, xmlschema, grinder_class):
    grinder_instance = grinder_class.return_value
    grinder_instance.submit.return_value = grinder.GrinderTaskId('test_id')
    grinder_instance.task_result.return_value = grinder.Result(states.PENDING, 'message')

    response = client.post('/tasks', data={
        'type': TASK_NAME,
        'uid': TEST_UID,
        'branch': TEST_BRANCH_ID,
        'commit': TEST_COMMIT_ID,
        'subset': 'domain'
    })
    assert response.status_code == 200

    # test grinder

    grinder_instance.submit.assert_called_once_with({
        'type': TASK_NAME,
        'taskId': TEST_TASK_ID,
        'branch': str(TEST_BRANCH_ID),
        'commitId': TEST_COMMIT_ID,
        'subset': 'domain',
        'experiment': '',
        'tested': True
    })

    # test brief context

    root = ET.fromstring(response.data)
    xmlschema.assertValid(root)

    check_context(root)

    # test full context and result

    response = client.get('/tasks/' + str(TEST_TASK_ID), data={
        'uid': TEST_UID
    })
    assert response.status_code == 200

    root = ET.fromstring(response.data)
    xmlschema.assertValid(root)

    check_context(root)
