import hashlib, json, os, sys, time, urllib.request
from asc import rufe
VER_LOC = '13ad3d75-78d2-46ef-8936-f68b4d5f9a0e'
ORDNER = os.path.expanduser('~/workspace/git.mqtec.de/software/amj-namaztimes-ds/app/store/screenshots-6.9')
TYP = sys.argv[1] if len(sys.argv) > 1 else 'APP_IPHONE_67'

s, j = rufe('GET', f'/v1/appStoreVersionLocalizations/{VER_LOC}/appScreenshotSets')
satz = next((d['id'] for d in j.get('data', []) if d['attributes']['screenshotDisplayType'] == TYP), None)
if satz is None:
    s, j = rufe('POST', '/v1/appScreenshotSets', {'data': {'type': 'appScreenshotSets', 'attributes': {'screenshotDisplayType': TYP},
        'relationships': {'appStoreVersionLocalization': {'data': {'type': 'appStoreVersionLocalizations', 'id': VER_LOC}}}}})
    if s != 201: print('FAIL Satz', s, json.dumps(j)[:400]); sys.exit(1)
    satz = j['data']['id']
print('Satz', TYP, satz)

# vorhandene entfernen, damit der Lauf wiederholbar ist
s, j = rufe('GET', f'/v1/appScreenshotSets/{satz}/appScreenshots')
for d in j.get('data', []): rufe('DELETE', f"/v1/appScreenshots/{d['id']}")

for name in sorted(f for f in os.listdir(ORDNER) if f.endswith('.png')):
    daten = open(os.path.join(ORDNER, name), 'rb').read()
    s, j = rufe('POST', '/v1/appScreenshots', {'data': {'type': 'appScreenshots', 'attributes': {'fileName': name, 'fileSize': len(daten)},
        'relationships': {'appScreenshotSet': {'data': {'type': 'appScreenshotSets', 'id': satz}}}}})
    if s != 201: print('FAIL anlegen', name, s, json.dumps(j)[:300]); continue
    bid = j['data']['id']
    for op in j['data']['attributes']['uploadOperations']:
        teil = daten[op['offset']:op['offset'] + op['length']]
        req = urllib.request.Request(op['url'], data=teil, method=op['method'], headers={h['name']: h['value'] for h in op['requestHeaders']})
        urllib.request.urlopen(req, timeout=120).read()
    s, j = rufe('PATCH', f'/v1/appScreenshots/{bid}', {'data': {'type': 'appScreenshots', 'id': bid, 'attributes': {'uploaded': True, 'sourceFileChecksum': hashlib.md5(daten).hexdigest()}}})
    print(('OK   ' if s == 200 else 'FAIL ') + name, s)

time.sleep(15)
s, j = rufe('GET', f'/v1/appScreenshotSets/{satz}/appScreenshots')
for d in j.get('data', []):
    a = d['attributes']; print(' ', a['fileName'], a.get('assetDeliveryState', {}).get('state'), a.get('assetDeliveryState', {}).get('errors'))
