# Passerelle - uniform access to data and services
# Copyright (C) 2018  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; exclude 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.deepcopy of the GNU Affero General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import os
import stat

import pytest

import tests.utils
from passerelle.apps.actesweb.models import ActesWeb


def get_test_base_dir(name):
    return os.path.join(os.path.dirname(__file__), 'data', name)


def get_file_from_test_base_dir(filename):
    path = os.path.join(get_test_base_dir('actesweb'), filename)
    with open(path) as fd:
        return fd.read()


@pytest.fixture
def actesweb(db):
    return tests.utils.make_resource(ActesWeb, **{'slug': 'test'})


PAYLOAD = [
    {'birth': json.loads(get_file_from_test_base_dir('payload_birth.json'))},
    {'mariage': json.loads(get_file_from_test_base_dir('payload_mariage.json'))},
    {'death': json.loads(get_file_from_test_base_dir('payload_death.json'))},
]


@pytest.fixture(params=PAYLOAD)
def payload(request):
    return request.param


def get_demand_filepath(con, demand_id):
    filename = '_'.join(demand_id.split('_')[1:])
    return os.path.join(con.basepath, filename)


def assert_file_content_values(filename, expectations):
    with open(filename, encoding='iso-8859-15') as fp:
        for line in fp.readlines():
            field, value = line.split('=')
            if field in expectations:
                assert value.strip() == expectations[field]


def test_demand_creation(app, payload, actesweb):
    url = '/actesweb/test/create/'
    if 'birth' in payload:
        response = app.post_json(url, params=payload['birth'])
        demand_id = response.json['data']['demand_id']
        demfile = get_demand_filepath(actesweb, demand_id)
        assert_file_content_values(
            demfile,
            dict(
                DEMANDEUR_CIVILITE="Madame",
                DEMANDEUR_NOM_USAGE="W'hatever?",
                DEMANDEUR_PRENOMS="Kim Chelsea",
                DEMANDEUR_ADRESSE1="37 Rue de l'Aigle Blanc",
                DEMANDEUR_VILLE="Nancy",
                DEMANDEUR_CP="54000",
                DEMANDEUR_PAYS="France",
                DEMANDEUR_TEL="+33 6 55 44 22 11",
                DEMANDEUR_ADR="chelsea@whatever.com",
                DEMANDE_NOM="Whatever",
                DEMANDE_PRENOMS="Kevin",
                DEMANDE_DATE_EVENEMENT="20120714",
                TYPE_DEMANDE="Copie Integrale",
                ACTE="NA",
                NB="1",
                LIEU_EVENEMENT="Nancy",
                PERE_NOM="Smith",
                PERE_PRENOMS="John Oliver",
                MERE_NOM="Smith",
                MERE_PRENOM="Kim",
                DEMANDE_SEXE="m",
            ),
        )
    elif 'mariage' in payload:
        response = app.post_json(url, params=payload['mariage'])
        demand_id = response.json['data']['demand_id']
        demfile = get_demand_filepath(actesweb, demand_id)
        assert_file_content_values(
            demfile,
            dict(
                DEMANDEUR_CIVILITE="Madame",
                DEMANDEUR_NOM_USAGE="Whatever",
                DEMANDEUR_NOM="Bar",
                DEMANDEUR_PRENOMS="Zoé",
                DEMANDEUR_ADRESSE1="169, rue du Château",
                DEMANDEUR_VILLE="Nancy",
                DEMANDEUR_CP="54001",
                DEMANDEUR_PAYS="France",
                DEMANDEUR_TEL="+33 6 55 44 22 11",
                DEMANDEUR_ADR="chelsea@whatever.com",
                DEMANDE_NOM="Whatever",
                DEMANDE_PRENOMS="Kevin",
                DEMANDE_DATE_EVENEMENT="20120714",
                TYPE_DEMANDE="Copie Integrale",
                ACTE="MA",
                NB="1",
                LIEU_EVENEMENT="Nancy",
                PERE_NOM="Smith",
                PERE_PRENOMS="John Oliver",
                MERE_NOM="Smith",
                MERE_PRENOM="Kim",
                DEMANDE_SEXE="m",
                CONJOINT_NOM="Contrao",
                CONJOIN_PRENOMS="Chelsea",
                CONJOINT_PERE_NOM="Scaramucci",
                CONJOINT_PERE_PRENOMS="Antonio",
                CONJOINT_MERE_NOM="Scaramucci",
                CONJOINT_MERE_PRENOMS="Marguerite",
            ),
        )
    else:
        response = app.post_json(url, params=payload['death'])
        demand_id = response.json['data']['demand_id']
        demfile = get_demand_filepath(actesweb, demand_id)
        # make sure only owner can read file
        assert bool(os.stat(demfile).st_mode & stat.S_IRUSR)
        # make sure group can read and write (move) file
        assert bool(os.stat(demfile).st_mode & stat.S_IRGRP)
        assert bool(os.stat(demfile).st_mode & stat.S_IWGRP)
        # and no others
        assert not bool(os.stat(demfile).st_mode & stat.S_IRWXO)
        assert_file_content_values(
            demfile,
            dict(
                DEMANDEUR_CIVILITE="Madame",
                DEMANDEUR_NOM_USAGE="Whatever",
                DEMANDEUR_PRENOMS="Kim Chelsea",
                DEMANDEUR_ADRESSE1="37 Rue de l'Aigle Blanc",
                DEMANDEUR_VILLE="Nancy",
                DEMANDEUR_CP="54000",
                DEMANDEUR_PAYS="France",
                DEMANDEUR_TEL="+33 6 55 44 22 11",
                DEMANDEUR_ADR="chelsea@whatever.com",
                DEMANDE_NOM="Whatever",
                DEMANDE_PRENOMS="Kevin",
                DEMANDE_DATE_EVENEMENT="20120714",
                TYPE_DEMANDE="Extrait sans filiation",
                ACTE="DE",
                NB="1",
                LIEU_EVENEMENT="Nancy",
                DEMANDE_SEXE="m",
            ),
        )
