"""Test the formel update API flow"""
import urllib.request, urllib.parse, json, sys

BASE = 'http://127.0.0.1:5000'

# Login
s = urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
req = urllib.request.Request(BASE + '/auth/login',
    data=b'email=fk@kpt-consulting.de&password=kpt2024')
s.open(req)

# Add a test position
data = urllib.parse.urlencode({
    'pos_nr': 'FORMEL-TEST', 'kurztext': 'Test Formel',
    'einheit': 'M', 'einzelpreis': '50',
    'faktor': '1.0', 'laenge': '5.0'
}).encode()
req = urllib.request.Request(BASE + '/projekt/1/1/position/hinzufuegen',
    data=data, method='POST')
r = s.open(req)
print('Add position:', r.status)

# Get positions
req = urllib.request.Request(BASE + '/projekt/1/1/positionen')
r = s.open(req)
positions = json.loads(r.read())
pos_id = positions[-1]['id']
print(f'Position ID: {pos_id}')

# Set formel_typ to frei
body = json.dumps({'field': 'formel_typ', 'value': 'frei'}).encode()
req = urllib.request.Request(
    BASE + f'/projekt/1/1/position/{pos_id}/update-cell',
    data=body, method='POST',
    headers={'Content-Type': 'application/json'})
r = s.open(req)
resp = json.loads(r.read())
print(f'After formel_typ=frei: menge={resp.get("menge")} gp={resp.get("gesamtpreis")} hinten={resp.get("menge_hinten")}')

# Set formel value
body = json.dumps({'field': 'formel', 'value': '2*3+1'}).encode()
req = urllib.request.Request(
    BASE + f'/projekt/1/1/position/{pos_id}/update-cell',
    data=body, method='POST',
    headers={'Content-Type': 'application/json'})
r = s.open(req)
resp = json.loads(r.read())
print(f'After formel=2*3+1: menge={resp.get("menge")} gp={resp.get("gesamtpreis")} hinten={resp.get("menge_hinten")}')

# Cleanup: delete test position
req = urllib.request.Request(
    BASE + f'/projekt/1/1/position/{pos_id}/loeschen', method='POST')
s.open(req)
print(f'Test position {pos_id} deleted')
print('\nSUCCESS: menge_hinten was correctly returned in response')
