import httpx
import re
import json
import os
from ext import Order

headers = {'Host': 'reg.furizon.net', 'Authorization': 'Token [REDACTED]'}
output = {}

# uid starts from 2 because of the two hard-coded badge numbers
i = 2

# Furizon was 200 orders, plenty of pages to go through
for x in range(10):
	r = httpx.get(f'https://reg.furizon.net/api/v1/organizers/furizon/events/beyond/orders/?page={x+1}', headers=headers)
	if r.status_code == 404: break
	
	data = r.json()
	
	for r in data['results']:
		badge = open('template.svg', 'r').read()
		order = Order(r)
		if not order: continue
		if order.status != 'paid': continue
	
		# These orders had an hard-coded UID of 1 and 2
		if order.code == 'HWUC9':
			uid = 2
		elif order.code == 'ZUESS':
			uid = 1
		else:
			i += 1
			uid = i
	
		output[uid] = (order.code, order.name)
	
		# Replace the various texts and colors inside of the svg
		badge = badge.replace('#deadbe', {None: '#546e7a', 'normal': '#8e24aa', 'super': '#fb8c00'}[order.sponsorship])
		badge = badge.replace('#SPONSOR_STATUS', {None: 'Regular', 'normal': 'Sponsor', 'super': 'Supersponsor'}[order.sponsorship])
		badge = badge.replace('#ATTEND_NAME', order.name)
		badge = badge.replace('#CODE', order.code)
		badge = badge.replace('#UID', f'{uid:03}')
		badge = badge.replace('flag.svg', f"../flags/{order.country.lower()}.svg")

		# Change the background of the badge depending on staff role
		if order.ans('staff_role'):
			if 'main staff' in order.ans('staff_role'):
				badge = badge.replace('badge_viola.png', 'badge_rosso.png')
			elif 'staff' in order.ans('staff_role'):
				badge = badge.replace('badge_viola.png', 'badge_azzurro.png')

		# Change the background also based on sponsorship
		elif order.sponsorship == 'normal':
			badge = badge.replace('badge_viola.png', 'badge_viola.png')
		elif order.sponsorship == 'super':
			badge = badge.replace('badge_viola.png', 'badge_giallo.png')
		else:
			badge = badge.replace('badge_viola.png', 'badge_verde.png')
		
		# Fix paths so that they are correct
		badge = badge.replace('badge_', '../badge_')
		
		# Add the propics
		if order.propic:
			badge = badge.replace('avatar.png', f"../propic/{order.propic}")
		else:
			badge = badge.replace('avatar.png', f"../avatar.png")

		# Save the badges
		with open(f"output/{uid:03}_{order.code}.svg", 'w') as f:
			f.write(badge)

# Use inkscape to convert all badges to pdf and then create a unique file
os.system('inkscape --actions="export-type:pdf;export-do;" output/*.svg')
os.system('rm output/*.svg')
os.system('pdfunite output/* combined.pdf')
