#!/usr/bin/python3

import datetime
import json
import os
import requests
import subprocess
import time
import traceback

# Registrando model printing 

try:
    url = "{{ quotas_endpoint }}/api/printings/"
    api_key = "{{ quotas_api_token }}"
    headers = {'Authorization': api_key}

    user = os.getenv('TEAUSERNAME')
    datafile = os.getenv('TEADATAFILE')
    pages = subprocess.check_output(['/usr/local/bin/pkpgcounter', datafile])
    copies = os.getenv('TEACOPIES')
    printer = os.getenv('TEAPRINTERNAME')
    jobid = os.getenv('TEAJOBID')
    host = os.getenv('TEACLIENTHOST')
    filename = os.getenv('TEATITLE')
    filesize = os.getenv('TEAJOBSIZE')

    body = {'user': user,
            'pages': int(pages),
            'copies': copies,
            'printer': printer,
            'jobid': jobid,
            'host': host,
            'filename': filename,
            'filesize': filesize
            }

    response = requests.post(url, headers=headers, data=body)
    status_code = response.status_code

    if status_code == 200:
        data = response.json()

        if data["latest_status"] == "sent_to_printer_queue":
            exit(0)

        printing_id = str(data["printing_id"])

        for i in range(120):
            time.sleep(1)
            response = requests.get(url + printing_id, headers=headers)
            latest_status = response.json()["latest_status"]

            if latest_status == "sent_to_printer_queue":
                exit(0)

            if latest_status == "cancelled_not_authorized":
                exit(-1)

        body  = {"status": "cancelled_timeout"}
        requests.post(url + printing_id, headers=headers, data=body)

        exit(-1)

    else:
        log = "Status code returned: " + str(status_code)
        file_object = open("/tmp/tea4cups.log", "a+")
        file_object.write("\n" + log)
        file_object.close()
        body  = {"status": "printer_problem"}
        requests.post(url + printing_id, headers=headers, data=body)

        exit(-1)
        
except Exception as err:
    log = traceback.format_exc()
    file_object = open("/tmp/tea4cups.log", "a+")
    datetime = datetime.datetime.now()
    file_object.write("\n[{}]\n".format(datetime) + log)
    file_object.close()

    body  = {"status": "printer_problem"}
    requests.post(url + printing_id, headers=headers, data=body)

    exit(-1)
