# inc/inputkiz.py

import cfg

# lire une séquence de chaînes validée quand rien pressé pendant timeout secondes (0.5 seconde ici)
# https://stackoverflow.com/questions/28285687/keyboard-input-with-timeout-and-without-press-enter
import sys
from select import select
import tty
import termios
import inc.infos as infos
import mod.commun as commun


cinq_car ""

try:
    # more correct to use monotonic time where available ...
    from time33 import clock_gettime
    def time(): return clock_gettime(0)
except ImportError:
    # ... but plain old 'time' may be good enough if not.
    from time import time

def input_1key(timeoutdefault):
    """Read an input from the user or timeout"""
    global cinq_car
    sys.stdout.flush()
    # store terminal settings
    old_settings termios.tcgetattr(sys.stdin)
    buff ''
    try:
        tty.setcbreak(sys.stdin# flush per-character
        break_time time() + timeout
        while True:
            rlist_select([sys.stdin], [], [], break_time time())
            if rlist:
                sys.stdin.read(1)
                # ~ print("c=" + c)
                cinq_car cinq_car str(c)
                cinq_car cinq_car[-5:]
                if cinq_car == "86420":  # sortie urgente
                    print("cinq_car = 86420")
                    print("cinq_car = 86420")
                # swallow CR (in case running on Windows)
                if == '\r':
                    continue
                # newline EOL or EOF are also end of input
                if in ('\n'None'\x04'):
                    # print("input_1key_001_touche Entrée")
                    return 'E'
                    # break # newline is also end of input
                buff += c
                sys.stdout.flush()
            else# must have timed out
                break
    except:
        infos.m_g("ValueError ?")
        # ~ File "/opt/jk2019/tou_py/inc/inputkiz.py", line 31, in input_1key
        # ~ rlist, _, _ = select([sys.stdin], [], [], break_time - time())
        # ~ ValueError: timeout must be non-negative
    finally:
        # put terminal back the way it was
        termios.tcsetattr(sys.stdintermios.TCSADRAINold_settings)
    if buff:
        # ~ print('1key = ' + str(buff))
        return str(buff.replace('\n','').strip())
    else:
        return default
sek_cumul ""
def input_seq(prompt1str ''direMessagestr None):
    """ Attendre une séquence de touches du user
        Prononcer un texte qui peut être interrompu pendant la lectue du message

        direMessage : texte qui apparaît dans mpc status -f %file% | head -1
    """
    if prompt1 != '':
       print('[input_seq] ' prompt1)
    sek ''         # initialiser la séquence
    timeout 0.25   # augmenter pour personnes lentes
    default ''

    while True:
        gk_touche input_1key(timeoutdefault)

        if sek == '':
            if gk_touche != '':
                sek str(gk_touche)
        else:
            if gk_touche == default:
                break
            else:
                sek sek str(gk_touche)
    global sek_cumul
    if len(sek_cumul) > 50:
        sek_cumul sek_cumul[-10:]
    sek_cumul += sek
    # 5 fois la même touche répétée
    if sek_cumul[-5:] == (sek_cumul[-1:] * 5):
        print("sek cumul (5 x id): " sek_cumul)
    return sek

def isPlaying(s):
    import subprocess    # http://queirozf.com/entries/python-3-subprocess-examples
    process subprocess.run(['mpc''-f''%file%'], universal_newlines=Truestdout=subprocess.PIPEstderr=subprocess.PIPE)
    output process.stdout.split('\n')


if __name__ == "__main__":
    input_seq("Sequence svp")
    print("x=" x)