# -*- coding: utf-8 -*- vim:sw=4:sts=4:et:ai:si:sta:fenc=utf-8
import i_need_py23

"""Des fonctions pour la saisie de valeurs.
"""

__all__ = ('I_BATCH', 'I_AUTO', 'I_NORMAL', 'I_INTER',
           'set_interaction', 'check_interaction',
           'is_yes', 'is_no', 'is_quit',
           'ask_yesno', 'ask_yesquit', 'read_value',
           )

import os, sys, re

from base import isnum
from uio import _s, _u, uinput
from output import eprint, V_ERROR, eerror

################################################################################
# Niveau d'interaction, pour la saisie de valeurs

I_BATCH = 0
I_AUTO = 1
I_NORMAL = 2
I_INTER = 3

I_MIN = I_BATCH
I_DEF = I_NORMAL
I_MAX = I_INTER

def get_interaction(): return int(os.environ.get('__interaction', I_DEF))
def _set_interaction(i): os.environ['__interaction'] = str(i)
def inc_interaction():
    i = get_interaction()
    if i < I_MAX: _set_interaction(i + 1)
def dec_interaction():
    i = get_interaction()
    if i > I_MIN: _set_interaction(i - 1)
def set_interaction(i):
    if not isnum(i) and not i: i = I_DEF
    elif i in ('-b', '--batch'): i = I_MIN
    elif i in ('-y', '--automatic'): return dec_interaction()
    elif i in ('-i', '--interactive'): return inc_interaction()
    elif i in ('-c', '--default'): i = I_DEF
    else: return False
    _set_interaction(i)
    return True

INTERACTION_OPTS = ('-b', '--batch',
                    '-y', '--automatic',
                    '-i', '--interactive'
                    )

RE_NUM = re.compile(r'\d+$')
def check_interaction(i=I_NORMAL):
    if isnum(i) or RE_NUM.match(i) is not None: return get_interaction() >= int(i)
    elif i in ('-b', '--batch'): return get_interaction() >= I_BATCH
    elif i in ('-y', '--automatic'): return get_interaction() >= I_AUTO
    elif i in ('-c', '--default'): return get_interaction() >= I_NORMAL
    elif i in ('-i', '--interactive'): return get_interaction() >= I_INTER
    else: return True

_set_interaction(get_interaction()) # configurer l'interaction par défaut

# réponses
def is_yes(r):
    return _s(r).lower() in ('o', 'oui', 'y', 'yes', 'v', 'vrai', 't', 'true', '1')

def is_no(r):
    return _s(r).lower() in ('n', 'non', 'no', 'f', 'faux', 'false', '0')

def is_quit(r):
    return is_no(r) or _s(r).lower() in ('q', 'quit', 'quitter')

# lecture d'une réponse
def ask_yesno(msg=u"Voulez-vous continuer?", default=None, minlevel=I_NORMAL):
    if default is None: default='N'
    default = _s(default).upper()

    if not check_interaction(minlevel):
        if default == 'C': return True
        elif default == 'X': return False
        else: return is_yes(default)

    if default == 'C': default = 'N'
    elif default == 'X': default = 'O'
    prompt = is_yes(default) and u"[On]" or u"[oN]"
    eprint(u"%s %s " % (_u(msg), prompt), V_ERROR, False, True)
    return is_yes(uinput() or default)

def ask_yesquit(msg=u"Voulez-vous continuer?", default=None, minlevel=I_NORMAL):
    if default is None: default = 'Q'
    default = _s(default).upper()

    if not check_interaction(minlevel):
        if default == 'C': return True
        elif default == 'X': return False
        else: return is_yes(default)

    if default == 'C': default = 'Q'
    elif default == 'X': default = 'O'
    prompt = is_yes(default) and u"[Oq]" or u"[oQ]"
    eprint(u"%s %s " % (_u(msg), prompt), V_ERROR, False, True)
    return is_yes(uinput() or default)

def read_value(msg=u"Entrez la valeur", default=None, required=True, minlevel=I_NORMAL):
    if not check_interaction(minlevel):
        if required and default is None:
            raise ValueError("default must not be empty")
        return default

    if default is None: prompt = u''
    else: prompt = u' [%s]' % _u(default)
    msg = u"%s%s: " % (_u(msg), prompt)
    while True:
        eprint(msg, V_ERROR, False, True)
        r = uinput()
        if r: break
        elif required and default is None:
            eerror(u"Vous devez entrer une valeur non vide")
        else:
            r = default
            break
    return r
