#!/usr/bin/python3 -u

from selenium import webdriver
from selenium.webdriver.common.print_page_options import PrintOptions
from selenium.webdriver.firefox.service import Service
from tqdm import tqdm
import base64
import sys
import time

if len(sys.argv) != 4:
    print(f'Usage: {sys.argv[0]} <dates file> <hour> <delay in seconds (to allow page to render chant notation)>\nhour ∈ [matutinum, laudes, prima, tertia, sexta, nona, vesperas, completorium]', file=sys.stderr)
    sys.exit(1)

dates_file = sys.argv[1]
dates = []
with open(dates_file, 'r') as f:
    for line in f:
        dates.append(line.strip())
hour = sys.argv[2]
delay = int(sys.argv[3])

url_stub = f'https://breviariumgregorianum.com/?office={hour}&toggledParam=false&compact=compact&lang=la&nabc=false&priest=true&date='

firefox_service = Service(executable_path="/usr/bin/geckodriver")
driver = webdriver.Firefox(service = firefox_service)

print_options = PrintOptions()

pbar = tqdm(dates)
for date in pbar:
    pbar.set_postfix_str(f'Processing {date}…')
    
    driver.get(url_stub + date)
    # wait for the page to render chant notation
    time.sleep(delay)

    pdf_filename = date + ' ' + driver.title[:-25] + '.pdf'

    pbar.set_postfix_str(f'Printing to {pdf_filename}…')
    print_options.file_name = pdf_filename
    pdf = driver.print_page(print_options)
    
    # convert & save the PDF to binary file
    pdf_bytes = base64.b64decode(pdf)    # convert to bytes; 🎩-tip: https://stackoverflow.com/a/77631772/1429450 and https://www.selenium.dev/documentation/webdriver/interactions/print_page/#codeModal_1045ec892e9a3bf2421fbe6cd352bb8b:~:text=the%20print%20command%20will%20return%20the%20PDF%20data%20in%20base64%2Dencoded%20format
    with open(pdf_filename, 'wb') as f:
        f.write(pdf_bytes)

driver.quit()
