import requests
import urllib.request
import xml.etree.ElementTree as ET
import subprocess
from pathlib import Path
import os

#a.digi4school.at/ebook/791/?page=52

maxpages = 52

contentdir = "./pages"							# ./pages													dir
pagedirtemplate = contentdir + "/{}"			# ./pages/1				pagenr								dir
subdirtemplate 	= pagedirtemplate + "/{}"		# ./pages/1/img 		pagenr, "img"						dir

svgsavetemplate = pagedirtemplate + "/{}.{}"	# ./pages/1/1.svg 		pagenr, pagenr, "svg"				file
imgsavetemplate = subdirtemplate + "/{}.{}"		# ./pages/1/img/1.png 	pagenr, "img", imgnr, "png"			file

# https://a.trauner-digibox.com/ebook/584/1/1.svg
# ebook number, page number, page number, sxtension
svgurltemplate = "https://a.digi4school.at/ebook/{}/{}/{}.{}"

# https://a.trauner-digibox.com/ebook/584/1/img/1.png
# ebook number, page number, img kind, img number, extension
imgurltemplate = "https://a.digi4school.at/ebook/{}/{}/{}/{}.{}"

ebooknr = "791"

if not os.path.exists(contentdir):
	os.makedirs(contentdir)

for pagenr in range(1, maxpages + 1):
	cookies = {
		'digi4s': '1430266494%2c791%2c10uc5ab2f1fy%2c96060%20{421%201576046595%203D5C8CD3A0798712D5185FC95C9A8955A2AFCF43}',
		'digi4b' : '96060%2c1575960190%20{982%200%20608298EAE5D829FFD9E417AFF76D8A644DA01134}'
	}

	headers = {'User-Agent': 'Mozilla/5.0 (Linux; Android 5.1.1; SM-G928X Build/LMY47X) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.83 Mobile Safari/537.36'}

	print(pagenr)

	if not os.path.exists(pagedirtemplate.format(pagenr)):
		os.makedirs(pagedirtemplate.format(pagenr))

	if not os.path.exists(subdirtemplate.format(pagenr, "img")):
		os.makedirs(subdirtemplate.format(pagenr, "img"))
		
		if not os.path.exists(subdirtemplate.format(pagenr, "shade")):
			os.makedirs(subdirtemplate.format(pagenr, "shade"))

		response = requests.get(svgurltemplate.format(ebooknr, pagenr, pagenr, "svg"), headers=headers, cookies=cookies)   
		if (response.status_code != 404):
			with open(svgsavetemplate.format(pagenr, pagenr, "svg"), 'wb') as f:
				f.write(response.content)

		imagecount = 0

		with open(svgsavetemplate.format(pagenr, pagenr, "svg")) as f:
		    contents = f.read()
		    imagecount = contents.count("<image")

		for imgnr in range(0, imagecount + 1):
			print("+{}".format(imgnr))

			response = requests.get(imgurltemplate.format(ebooknr, pagenr, "img", imgnr, "png"), headers=headers, cookies=cookies)   	
			if (response.status_code != 404):
				with open(imgsavetemplate.format(pagenr, "img", imgnr, "png"), 'wb') as f:
					f.write(response.content)

			response = requests.get(imgurltemplate.format(ebooknr, pagenr, "shade", imgnr, "png"), headers=headers, cookies=cookies)   	
			if (response.status_code != 404):
				with open(imgsavetemplate.format(pagenr, "shade", imgnr, "png"), 'wb') as f:
					f.write(response.content)

		subprocess.call(["rsvg-convert", "-f", "pdf", "-o", "{}.pdf".format(pagenr), svgsavetemplate.format(pagenr, pagenr, "svg")])