#!/bin/bash /usr/scripts/python.sh
# -*- mode: python; coding: utf-8 -*-
#
# total_impression.py
# -----------------
#
# Copyright (C) 2007 Michel Blockelet <blockelet@crans.org>
#
# Revu et corrigé en 2015 par Gabriel Détraz
# This file is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This file 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 General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Street #330, Boston, MA 02111-1307, USA.

u"""Ce script permet de calculer les mouvements totaux des comptes d'impression.

Utilisation : %(prog)s [-h] [-v[v]] [date de debut [date de fin]]

Options :
 -h  : Afficher cette aide
 -v  : Afficher les totaux par personne
 -vv : Afficher tous les mouvements par personne

Les dates doivent etre de la forme jj/mm/aaaa."""

import sys
from lc_ldap import shortcuts
from gestion.affich_tools import cprint
import time

ldap = shortcuts.lc_ldap_admin()

def datestrtoint(strdate):
    u""" Convertit une date en entier. """
    date = strdate.split('/')
    return int(date[0]) + int(date[1])*100 + int(date[2])*10000

def soldes_adherent(dlinf, dlsup, adherent, verbose):
    u""" Cherche les modifications de solde. """

    totaldebit = 0
    totalcredit = 0

    for hist in adherent['historique']:
        sep = ' '
        champ = hist.replace(',', '').replace(': ', '').split(sep)
        if datestrtoint(champ[0]) >= dlinf and (dlsup == 0 or datestrtoint(champ[0]) <= dlsup):
            if champ[3] == 'debit':
                if verbose >= 2:
                    try:
                        cprint(hist, 'rouge')
                    except:
                        cprint('Non affichable : ' + sep.join(champ[:4]), 'rouge')
                totaldebit += float(champ[4])
            elif champ[3] == 'credit':
                if verbose >= 2:
                    try:
                        cprint(hist, 'vert')
                    except:
                        cprint('Non affichable : ' + sep.join(champ[:4]), 'vert')
                totalcredit += float(champ[4])

    return totaldebit, totalcredit

def calcul_soldes():
    u""" Calcule les totaux. """

    verbose = 0
    dlinf = 0
    dlsup = 0

    sysargv = sys.argv
    if len(sysargv) > 1:
        if '-h' in sysargv:
           cprint(__doc__ % { 'prog': sysargv[0] }, 'bleu')
           sys.exit(1)
        if '-v' in sysargv:
           verbose = 1
           sysargv.remove('-v')
        if '-vv' in sysargv:
           verbose = 2
           sysargv.remove('-vv')
        if len(sysargv) > 1:
           strdlinf = sysargv[1]
           try:
               dlinf = datestrtoint(strdlinf)
           except:
               cprint('***** Date invalide : ' + strdlinf + ' *****', 'rouge')
               cprint(__doc__ % { 'prog': sysargv[0] }, 'bleu')
               sys.exit(1)
           if len(sysargv) > 2:
               strdlsup = sysargv[2]
               dlsup = datestrtoint(strdlsup)
               try:
                   dlsup = datestrtoint(strdlsup)
               except:
                   cprint('***** Date invalide : ' + strdlinf + ' *****', 'rouge')
                   cprint(__doc__ % { 'prog': sysargv[0] }, 'bleu')
                   sys.exit(1)

    totaldebit = 0
    totalcredit = 0

    liste = ldap.search(u"uid=*",sizelimit=10000)

    for adherent in liste:
        try:
            adhdebit, adhcredit = soldes_adherent(dlinf, dlsup, adherent, verbose)
            if adhdebit + adhcredit > 0 and adhdebit + adhcredit < 1000000: # On evite Toto Passoir
                if verbose >= 2:
                    cprint('-' * 40, 'cyan')
                if verbose >= 1:
                    name = unicode(adherent['prenom'][0]) + u" " + unicode(adherent['nom'][0])
                    cprint(u'Debit  total pour ' + name + u' : ' + unicode(adhdebit) + u' euros', 'rouge')
                    cprint(u'Credit total pour ' + name + u' : ' + unicode(adhcredit) + u' euros', 'vert')
                    cprint('=' * 40, 'bleu')
                totaldebit += adhdebit
                totalcredit += adhcredit
        except KeyError:
            pass
    if verbose >= 1:
        cprint('=' * 80, 'bleu')
    if dlinf == 0:
        cprint('Totaux :', 'cyan')
    else:
        if dlsup == 0:
            cprint('Totaux depuis le ' + strdlinf + ' :', 'cyan')
        else:
            cprint('Totaux entre le ' + strdlinf + ' et le ' + strdlsup + ' :', 'cyan')
    cprint('Debit  total : ' + str(totaldebit) + ' euros', 'rouge')
    cprint('Credit total : ' + str(totalcredit) + ' euros', 'vert')
    if verbose >= 1:
        cprint('=' * 80, 'bleu')

if __name__ == "__main__":
    calcul_soldes()
