#!/usr/bin/python3

import cgi, cgitb
from enum import IntEnum
import pcalc

gff = [ 'f_new_purchase', 'f_saas', 'f_devices', 'f_months', 'f_support', 'f_paywhole', 'f_bonus', 'f_distributor', 'f_extend' ]

glob_form_fields = {
        gff[0]: True,
        gff[1]: False,
        gff[2]: 10,
        gff[3]: 12,
        gff[4]: pcalc.Support.Standard,
        gff[5]: False,
        gff[6]: 0,
        gff[7]: False,
        gff[8]: 0
        }

print("Content-Type: text/html")    # HTML is following
print()                             # blank line, end of headers
print("<title>DT License price calculator</title>")
cgitb.enable()
form = cgi.FieldStorage()
err = False
for i in glob_form_fields.keys():
    if i not in form:
        print("<h1> Data error </h1>")
        print("<p>The required parameter not present in form: ", i, "</p>")
        err = True
if not err:
    glob_form_fields[gff[0]] = "true" == form.getvalue(gff[0])
    glob_form_fields[gff[1]] = "true" == form.getvalue(gff[1])
    glob_form_fields[gff[7]] = "true" != form.getvalue(gff[7])
    try:
        glob_form_fields[gff[8]] = int(form.getvalue(gff[8]))
    except ValueError:
        print("<h2> Length of extended NOSUPPORT period must be a number, using 0</h2>")
        glob_form_fields[gff[8]] = 0
    try:
        glob_form_fields[gff[2]] = int(form.getvalue(gff[2]))
    except ValueError:
        print("<h2> Number of devices must be a number, using 10</h2>")
        glob_form_fields[gff[2]] = 10
    try:
        glob_form_fields[gff[3]] = int(form.getvalue(gff[3]))
    except ValueError:
        print("<h2> Validity in months must be a number, using 12</h2>")
        glob_form_fields[gff[3]] = 12
    try:
        glob_form_fields[gff[4]] = int(form.getvalue(gff[4]))
    except ValueError:
        print("<h2> Support levels must be a number (", form.getvalue(gff[4]), "), using Standard (2)</h2>")
        glob_form_fields[gff[4]] = pcalc.Support.Standard
    if glob_form_fields[gff[4]] < pcalc.Support.Free or pcalc.Support.Premium < glob_form_fields[gff[4]]:
        print("<h2> Invalid support level, using Standard (2)</h2>")
        glob_form_fields[gff[4]] = pcalc.Support.Standard
    glob_form_fields[gff[5]] = "true" == form.getvalue(gff[5])
    try:
        glob_form_fields[gff[6]] = int(form.getvalue(gff[6]))
    except ValueError:
        print("<h2> Bonus must be a number, using 0</h2>")
        glob_form_fields[gff[6]] = 0
    resitems = pcalc.add_license_base(glob_form_fields[gff[0]], glob_form_fields[gff[1]], glob_form_fields[gff[2]], glob_form_fields[gff[3]], glob_form_fields[gff[4]], glob_form_fields[gff[5]], glob_form_fields[gff[6]], glob_form_fields[gff[7]], glob_form_fields[gff[8]])
    print("<ul>");
    for idx, msg in enumerate(resitems):
        if idx == len(resitems)-1:
            print("<li><b>", msg, "</b></li>")
        else:
            print("<li>", msg, "</li>")
    print("</ul>");
