import requests
import time
from datetime import datetime
import glob

tags = set()
for p in glob.glob("pressure-*.csv"):
    p = p.rstrip('.csv')
    parts = p.split('-', maxsplit=4)
    tags.add(parts[4])
print('Existing tags:', ', '.join(list(tags)))
tag = input("Tag? ")

def metrics():
    r = requests.get('http://succbone.lab.fa-fo.de/metrics').text
    res = {}
    for line in r.split('\n'):
        if '#' in line:
            line = line[:line.index('#')]
        line = line.strip()
        if not line:
            continue
        a, b = line.split(' ')
        a = a.strip()
        b = b.strip()
        res[a] = float(b)
    return res


f = None
prev = None
logging = None
buffer = []
while True:
    time.sleep(0.1)
    m = metrics()
    v = m['sem_pressure_mbar']
    if logging is None:
        if v < 800 and (prev is None or prev >= 800):
            logging = time.time()
            print('Starting log...')
            f = open(f'pressure-{datetime.now().isoformat()}-{tag}.csv', 'w')
            f.write('elapsed\tmbar\n')
            for t, v in buffer:
                f.write(f'{t-logging}\t{v}\n')
        else:
            buffer.append((time.time(), v))
    else:
        if v > 800:
            print('Vented')
            break

    prev = v
    if logging is not None:
        elapsed = time.time() - logging
        print(elapsed, m['sem_pressure_mbar'])
        f.write(f'{elapsed}\t{v}\n')
    else:
        print('waiting', m['sem_pressure_mbar'])
