"""Screenshots of the demo for the user guide: fetch each page with the session cookie, add <base> so styles and
scripts load from the server, run an optional script (open a dropdown...), photograph it with headless Chrome."""
import os, subprocess, sys
from PIL import Image

S = os.path.dirname(os.path.abspath(__file__))
JAR = os.path.join(S, "cj.txt")
CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
BASE = "http://127.0.0.1:8000"

SHOTS = [
    # name, url, height, script run after load (optional)
    ("login", "/login", 860, None, False),
    ("home", "/", 980, None, True),
    ("home-search", "/", 760, "var i=document.getElementById('home-search'); i.value='bill'; i.dispatchEvent(new Event('input'));", True),
    ("dashboard", "/dashboard", 1000, None, True),
    ("company", "/setup/company", 1100, None, True),
    ("branches", "/setup/branches", 600, None, True),
    ("users", "/setup/users", 620, None, True),
    ("license", "/setup/license", 900, None, True),
    ("coa", "/setup/accounts", 1100, None, True),
    ("taxes", "/setup/taxes", 600, None, True),
    ("currencies", "/setup/rates", 700, None, True),
    ("cost-centres", "/setup/cost_centres", 560, None, True),
    ("customers", "/setup/partners?type=customer", 760, None, True),
    ("products", "/setup/products", 760, None, True),
    ("invoices", "/invoices/out_invoice", 900, None, True),
    ("invoice-form", "/invoices/out_invoice/new", 900, None, True),
    ("invoice-view", "/invoices/view/{inv}", 1000, None, True),
    ("invoice-fx", "/invoices/view/{inv_fx}", 900, None, True),
    ("payment-form", "/payments/new?invoice_id={inv}", 700, None, True),
    ("cheques-received", "/cheques/received", 860, None, True),
    ("cheque-view", "/cheques/view/{cheque}", 900, None, True),
    ("statement", "/statements/customer/{cust}", 1000, None, True),
    ("credit", "/credit/", 800, None, True),
    ("orders", "/orders/sale", 760, None, True),
    ("order-view", "/orders/view/{so}", 900, None, True),
    ("recurring", "/recurring/", 700, None, True),
    ("bills", "/invoices/in_invoice", 800, None, True),
    ("mr", "/procurement/mr", 700, None, True),
    ("rfq", "/procurement/rfq", 700, None, True),
    ("po-view", "/orders/view/{po}", 900, None, True),
    ("vendors", "/vendors/", 800, None, True),
    ("stock", "/inventory/stock", 860, None, True),
    ("pickings", "/inventory/transfers?kind=out", 760, None, True),
    ("picking-view", "/inventory/transfers/{delivery}", 860, None, True),
    ("wtransfers", "/stock-transfers/", 640, None, True),
    ("wtransfer-view", "/stock-transfers/{wtransfer}", 800, None, True),
    ("landed", "/inventory/landed-costs", 640, None, True),
    ("pos", "/pos/", 760, None, True),
    ("crm", "/crm/", 900, None, True),
    ("jv-list", "/entries/", 760, None, True),
    ("jv-form", "/entries/new", 820, "setTimeout(function(){var r=document.querySelector('table[data-lines] tbody tr:not(.tpl)'); var i=r.querySelector('.cb-input'); i.focus(); i.value='ban'; i.dispatchEvent(new Event('input'));},50);", True),
    ("jv-view", "/entries/{jv}", 820, None, True),
    ("transfers", "/transfers/", 640, None, True),
    ("petty", "/petty-cash/", 760, None, True),
    ("petty-fund", "/petty-cash/funds/1", 1000, None, True),
    ("petty-voucher", "/petty-cash/funds/1/vouchers/new", 760, None, True),
    ("bank", "/bank/", 760, None, True),
    ("bank-statement", "/bank/1", 900, None, True),
    ("assets", "/assets/", 700, None, True),
    ("asset-view", "/assets/1", 1000, None, True),
    ("prepaid", "/prepaid/", 700, None, True),
    ("budget", "/budgets/1", 1000, None, True),
    ("fx", "/fx/", 900, None, True),
    ("closing", "/closing/", 1100, None, True),
    ("employees", "/hr/employees", 860, None, True),
    ("employee", "/hr/employees/1", 1100, None, True),
    ("employee-form", "/hr/employees/new", 1100, None, True),
    ("payroll", "/hr/payroll", 760, None, True),
    ("payroll-run", "/hr/payroll/{run}", 1100, None, True),
    ("payslip", "/hr/payslip/{slip}", 900, None, True),
    ("leave", "/hr/leave", 700, None, True),
    ("loans", "/hr/loans", 600, None, True),
    ("settlement-form", "/hr/settlements/new", 700, None, True),
    ("provisions", "/hr/reports/provisions", 860, None, True),
    ("hr-settings", "/hr/settings", 1000, None, True),
    ("reports-pl", "/reports/profit-loss", 1100, None, True),
    ("reports-bs", "/reports/balance-sheet", 1000, None, True),
    ("reports-tb", "/reports/trial-balance", 1000, None, True),
    ("reports-gl", "/reports/general-ledger", 900, None, True),
    ("reports-aged", "/reports/aged/receivable", 860, None, True),
    ("reports-vat", "/reports/vat", 1000, None, True),
    ("reports-cc", "/reports/profit-loss/cost-centres", 900, None, True),
    ("import", "/setup/import/", 900, None, True),
    ("wf-rules", "/setup/workflow", 1000, None, True),
    ("wf-mr", "/procurement/mr/{mr_wait}", 1100, None, True),
    ("wf-inbox", "/approvals", 860, None, True),
    ("home-ar", "/", 900, None, True),
    # approvals, projects, procurement, supplier portal, invoice types, security
    ("wf-rule", "/setup/workflow/rule/1", 1000, None, True),
    ("wf-roles", "/setup/workflow/roles", 800, None, True),
    ("projects", "/projects/", 560, None, True),
    ("project", "/projects/{project}", 1700, None, True),
    ("project-form", "/projects/{project}/edit", 1900, None, True),
    ("mr-actions", "/procurement/mr/{mr_wait}", 1100, None, True),
    ("rfq-form", "/procurement/rfq/{rfq_sealed}/edit", 1900, None, True),
    ("rfq-sealed", "/procurement/rfq/{rfq_sealed}", 1300, None, True),
    ("rfq-award", "/procurement/rfq/{rfq_award}", 1500, None, True),
    ("po-sent", "/orders/view/{hire_po}", 1500, None, True),
    ("grn", "/orders/grn/{grn}", 800, None, True),
    ("company-proc", "/setup/company", 2400, None, True),
    ("reg-form", "/supplier/register", 2100, None, False),
    ("registrations", "/vendors/registrations", 900, None, True),
    ("registration", "/vendors/registrations/{reg}", 1500, None, True),
    ("portal-login", "/portal/login", 700, None, False),
    ("portal-home", "/portal/", 1200, None, "vendor"),
    ("portal-rfq", "/portal/rfqs/{portal_rfq}", 1500, None, "vendor"),
    ("portal-order", "/portal/orders/{gulf_po}", 1300, None, "vendor"),
    ("portal-invoices", "/portal/invoices", 1000, None, "vendor"),
    ("portal-company", "/portal/company", 1200, None, "vendor"),
    ("ap-inbox", "/vendors/ap-inbox?state=all", 600, None, True),
    ("ap-view", "/vendors/ap-inbox/{ap}", 1100, None, True),
    ("bank-change", "/vendors/bank-changes/{bank_change}", 1100, None, True),
    ("inv-types", "/invoices/out_invoice/new?type=advance", 900, None, True),
    ("final-invoice", "/invoices/view/{final_inv}", 1200, None, True),
    ("final-print", "/invoices/print/{final_inv}", 1300, None, True),
    ("proforma", "/invoices/view/{proforma}", 900, None, True),
    ("advances", "/invoices/advances", 600, None, True),
    ("progress-inv", "/invoices/print/{progress_inv}", 1300, None, True),
    ("partner-ledger", "/reports/partner-ledger?side=customer", 1000, None, True),
    ("backups", "/setup/backups", 900, None, True),
]


DB = os.path.join(os.path.dirname(os.path.dirname(S)), "instance", "vertex.db")
# demo records each screenshot shows, found by what they are (ids change when the demo is rebuilt)
LOOKUPS = {
    "inv": "SELECT id FROM invoices WHERE kind='out_invoice' AND state='posted' AND invoice_type='standard' AND currency IS NULL "
           "AND amount_tax > 0 AND branch_id=1 AND id IN (SELECT invoice_id FROM invoice_lines GROUP BY invoice_id HAVING COUNT(*) >= 2) "
           "ORDER BY date DESC LIMIT 1",
    "inv_fx": "SELECT id FROM invoices WHERE kind='out_invoice' AND state='posted' AND currency IS NOT NULL ORDER BY id DESC LIMIT 1",
    "cheque": "SELECT id FROM cheques ORDER BY id DESC LIMIT 1",
    "cust": "SELECT partner_id FROM invoices WHERE kind='out_invoice' AND state='posted' GROUP BY partner_id ORDER BY COUNT(*) DESC LIMIT 1",
    "so": "SELECT id FROM orders WHERE kind='sale' AND state='confirmed' ORDER BY id LIMIT 1",
    "po": "SELECT id FROM orders WHERE kind='purchase' AND state='confirmed' AND rfq_id IS NOT NULL ORDER BY id LIMIT 1",
    "delivery": "SELECT id FROM pickings WHERE kind='out' AND state='done' ORDER BY id LIMIT 1",
    "wtransfer": "SELECT id FROM stock_transfers ORDER BY id DESC LIMIT 1",
    "jv": "SELECT id FROM moves WHERE move_type='entry' AND state='posted' AND journal_id IN (SELECT id FROM journals WHERE code='MISC') ORDER BY id DESC LIMIT 1",
    "run": "SELECT id FROM payroll_runs WHERE state IN ('posted','paid') AND branch_id=1 ORDER BY period DESC LIMIT 1",
    "slip": "SELECT pl.id FROM payroll_lines pl JOIN payroll_runs r ON r.id = pl.run_id WHERE r.state IN ('posted','paid') AND r.branch_id=1 ORDER BY r.period DESC, pl.id LIMIT 1",
    "mr_wait": "SELECT doc_id FROM approval_requests WHERE doc_type='mr' AND state='pending' ORDER BY id DESC LIMIT 1",
    "project": "SELECT id FROM projects WHERE code='PRJ-001'",
    "rfq_sealed": "SELECT id FROM rfqs WHERE sealed=1 AND opened_at IS NULL LIMIT 1",
    "rfq_award": "SELECT id FROM rfqs WHERE state='award_pending' LIMIT 1",
    "hire_po": "SELECT order_id FROM grns ORDER BY id LIMIT 1",
    "grn": "SELECT id FROM grns ORDER BY id LIMIT 1",
    "reg": "SELECT id FROM vendor_registrations WHERE state='submitted' LIMIT 1",
    "ap": "SELECT id FROM vendor_invoices ORDER BY id LIMIT 1",
    "bank_change": "SELECT id FROM bank_changes WHERE state='pending' LIMIT 1",
    "final_inv": "SELECT invoice_id FROM invoice_lines WHERE advance_invoice_id IS NOT NULL LIMIT 1",
    "proforma": "SELECT id FROM invoices WHERE invoice_type='proforma' LIMIT 1",
    "progress_inv": "SELECT id FROM invoices WHERE invoice_type='progress' AND state='posted' ORDER BY id DESC LIMIT 1",
    "portal_rfq": "SELECT id FROM rfqs WHERE sealed=1 AND opened_at IS NULL LIMIT 1",
    "gulf_po": "SELECT id FROM orders WHERE partner_id=(SELECT id FROM partners WHERE name_en='Gulf Safety Equipment Co.') AND sent_at IS NOT NULL ORDER BY id DESC LIMIT 1",
}


def resolve(url):
    import re, sqlite3
    con = sqlite3.connect(DB)
    def one(m):
        r = con.execute(LOOKUPS[m.group(1)]).fetchone()
        return str(r[0]) if r else "0"
    out = re.sub(r"\{(\w+)\}", one, url)
    con.close()
    return out


VJAR = os.path.join(S, "vj.txt")  # a vendor signed in on the supplier portal


def fetch(url, auth):
    args = ["curl", "-s", url]
    if auth:
        args[1:1] = ["-b", VJAR if auth == "vendor" else JAR]
    return subprocess.run(args, capture_output=True, text=True).stdout


def shoot(name, url, height, script, auth, lang="en"):
    url = resolve(url)
    html = fetch(BASE + url, auth)
    html = html.replace("<head>", f'<head><base href="{BASE}/">', 1)
    import re as _re  # the guide is taken with the demo login: leave out its "change the demo password" banner
    html = _re.sub(r'<div class="flash error">(?:(?!</div>).)*demo password(?:(?!</div>).)*</div>', "", html, flags=_re.S)
    if script:
        html = html.replace("</body>", f"<script>window.addEventListener('load',function(){{setTimeout(function(){{{script}}},250);}});</script></body>")
    path = os.path.join(S, "shots", f"{name}.html")
    with open(path, "w") as f:
        f.write(html)
    png = os.path.join(S, "shots", f"{name}.png")
    subprocess.run([CHROME, "--headless=new", "--disable-gpu", "--hide-scrollbars", "--force-device-scale-factor=1.5",
                    f"--window-size=1366,{height}", "--virtual-time-budget=3000", f"--screenshot={png}",
                    "file://" + path], capture_output=True)
    im = Image.open(png).convert("RGB")
    im.save(os.path.join(S, "shots", f"{name}.jpg"), quality=82, optimize=True)
    os.remove(png)
    os.remove(path)
    return im.size


if __name__ == "__main__":
    only = set(sys.argv[1:])
    for name, url, h, script, auth in SHOTS:
        if only and name not in only:
            continue
        if name == "home-ar":
            subprocess.run(["curl", "-s", "-b", JAR, "-c", JAR, BASE + "/lang/ar"], capture_output=True)
        print(name, shoot(name, url, h, script, auth))
        if name == "home-ar":
            subprocess.run(["curl", "-s", "-b", JAR, "-c", JAR, BASE + "/lang/en"], capture_output=True)
