# 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/>.

import datetime
import json

PAYLOAD = {
    "visite": {},
    "plan-aide": {"DemandeAsg": {"DateDebut": "%(datedebut)s", "DateFin": "%(datefin)s"}},
    "presentation-commission": {"OrdreJourAsg": {"DateDebut": "%(datedebut)s", "DateFin": "%(datefin)s"}},
    "decision-commission": {
        "DemandeAsg": {
            "EtatDecision": "R",
            "DateDebutNotification": "%(datedebut)s",
            "DateFinNotification": "%(datefin)s",
            "DateDebutDecision": "%(datedebut)s",
            "DateFinDecision": "%(datefin)s",
        }
    },
}


def get_dates(datedebut, datefin):
    if datedebut:
        datedebut = datedebut[0][:10]
    else:
        datedebut = (datetime.datetime.now() - datetime.timedelta(180)).strftime('%Y-%m-%d')

    if datefin:
        datefin = datefin[0][:10]
    else:
        datefin = (datetime.datetime.now() + datetime.timedelta(180)).strftime('%Y-%m-%d')

    return datedebut, datefin


def render_payload(suivi_type, datedebut, datefin):
    datedebut, datefin = get_dates(datedebut, datefin)
    payload = json.dumps(PAYLOAD[suivi_type]) % {'datedebut': datedebut, 'datefin': datefin}
    return json.loads(payload)


def suivi_output(suivi_type, data):
    suivi_type = suivi_type.replace('-', '_')
    return globals().get('suivi_%s_output' % suivi_type)(data)


def suivi_visite_output(data):
    results = []
    visites = data.get('VisiteAsgs')

    if visites:
        visites = visites.get('VisiteAsg')

    if visites:
        if not isinstance(visites, list):
            visites = [visites]
        for visite in visites:
            info = {}
            info['visite_date'] = visite['Rencontre']['Date']['@V']
            info['visite_heure'] = visite['Rencontre']['Heure']['@V']
            participants = visite.get('Participants', {})
            intervenants = []
            if isinstance(participants, dict):
                _intervenants = participants.get('ListeIntervenants', {}).get('Intervenant', [])
                if not isinstance(_intervenants, list):
                    _intervenants = [_intervenants]
                for _intervenant in _intervenants:
                    intervenant = {}
                    intervenant['id'] = _intervenant['PK']['IndexIntervenantSocial']['@V']
                    intervenant['nom'] = _intervenant['Nom']['@V']
                    intervenant['prenom'] = _intervenant['Prenom']['@V']
                    coords = _intervenant.get('Coordonnees', {})
                    intervenant['email'] = coords.get('Email', {}).get('@V', '')
                    intervenant['telephone'] = coords.get('Telephone', {}).get('@V', '')
                    intervenants.append(intervenant)
            info['visite_intervenants'] = intervenants
            select = {}
            select['integration_response_data_indexDemande'] = visite['VisiteDemandeAsg']['PK']['Index']['@V']
            # select['integration_response_data_indexBeneficiaire'] = \
            #    visite['VisiteDemandeAsg']['BeneficiaireAsgDemande']['IndividuBeneficiaire']['PK']['IndexIndividu']['@V']
            results.append(
                {
                    'data': info,
                    'select': select,
                    #    'debug': visite
                }
            )

    return results


def suivi_decision_commission_output(data):
    results = []

    dems = data.get('DemandeAsgs')

    if dems:
        dems = dems.get('DemandeAsg')

    if dems:
        if not isinstance(dems, list):
            dems = [dems]
        for dem in dems:
            info = {}
            suivi = dem.get('Suivi', {})
            if not suivi.get('Decision'):
                continue
            info['decision_v'] = suivi.get('Decision', {}).get('@I', '')
            info['decision_v_long'] = suivi.get('Decision', {}).get('@Lc', '')
            info['decision_commentairenotification'] = suivi.get('CommentaireNotification', {}).get('@V', '')
            info['decision_datenotification'] = (suivi.get('DateNotification') or {}).get('@V', '')
            info['decision_datedecision'] = (suivi.get('DateDecision') or {}).get('@V', '')
            # if not info['decision_datenotification'] or info['decision_v'] not in ('A', 'R'):
            #    continue
            select = {}
            select['integration_response_data_indexDemande'] = dem['PK']['Index']['@V']
            results.append(
                {
                    'data': info,
                    'select': select,
                    #'debug': dem
                }
            )

    return results


def suivi_plan_aide_output(data):
    results = []
    return results


def suivi_presentation_commission_output(data):
    results = []

    odjs = data.get('OrdreJourAsgs')

    if odjs:
        odjs = odjs.get('OrdreJourAsg')

    if odjs:
        if not isinstance(odjs, list):
            odjs = [odjs]
        for odj in odjs:
            info = {}
            info['presentation_dateseance'] = odj['DateSeance']['@V']
            select = {}
            select['integration_response_data_indexDemande'] = odj['OrdreJourAsgDemandeAsg']['PK']['Index'][
                '@V'
            ]
            # select['integration_response_data_indexBeneficiaire'] = \
            #    odj['OrdreJourAsgDemandeAsg']['BeneficiaireAsgDemande']['IndividuBeneficiaire']['PK']['IndexIndividu']['@V']
            results.append(
                {
                    'data': info,
                    'select': select,
                    #    'debug': odj
                }
            )

    return results
