# -*- coding: utf-8 -*-
# Passerelle - uniform access to data and services
# Copyright (C) 2015  Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

from __future__ import unicode_literals

import os
import json

import mock
import pytest

import utils

from passerelle.contrib.mdel.models import MDEL


@pytest.fixture
def mdel(db):
    return utils.setup_access_rights(MDEL.objects.create(slug='test'))


DEMAND_STATUS = {
    'closed': True,
    'status': 'accepted',
    'comment': 'dossier trait\xe9.'
}


@mock.patch('passerelle.contrib.mdel.models.Demand.get_status', lambda x: DEMAND_STATUS)
@mock.patch('passerelle.contrib.mdel.models.Demand.create_zip', lambda x, y: '1-14-ILE-LA')
def test_generic_payload_logging(caplog, app, mdel):
    filename = os.path.join(os.path.dirname(__file__), 'data', 'mdel', 'formdata.json')
    payload = json.load(file(filename))
    resp = app.post_json('/mdel/test/create', payload, status=200)
    assert resp.json['data']['demand_id'] == '1-14-ILE-LA'

    resp = app.get('/mdel/test/status', {'demand_id': '1-14-ILE-LA'})
    data = resp.json['data']

    assert data['closed'] is True
    assert data['status'] == 'accepted'
    assert data['comment'] == 'dossier trait\xe9.'

    records = [record for record in caplog.records() if record.name == 'passerelle.resource.mdel.test']
    for record in records:
        assert record.module == 'views'
        assert record.levelname == 'DEBUG'
        assert record.connector == 'mdel'
        if record.connector_endpoint_method == 'POST':
            assert 'endpoint POST /mdel/test/create' in record.message
            assert record.connector_endpoint == 'create'
        else:
            assert 'endpoint GET /mdel/test/status?demand_id=1-14-ILE-LA' in record.message
            assert record.connector_endpoint == 'status'
            assert record.connector_endpoint_url == '/mdel/test/status?demand_id=1-14-ILE-LA'
