import os, sys, time
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.service import Service

HERE = os.path.dirname(os.path.abspath(__file__))
GECKODRIVER = os.path.join(HERE, "geckodriver.exe")
BASE = "http://localhost:8000/field-capture.html?debug"

opts = Options()
opts.headless = False
svc = Service(executable_path=GECKODRIVER)
d = webdriver.Firefox(options=opts, service=svc)
d.set_window_size(480, 900)

d.get(BASE + "&_=" + str(int(time.time())))
time.sleep(2)
d.find_element(By.CSS_SELECTOR, '[data-action="newjob"]').click()
time.sleep(0.5)
d.find_element(By.CSS_SELECTOR, '[data-action="opensketch"]').click()
time.sleep(0.5)
d.execute_script("""
    const T = window.__test;
    const job = T.state.jobs[0];
    const sk = job.sketches[0];
    const c = document.createElement('canvas');
    c.width = 400; c.height = 300;
    const ctx = c.getContext('2d');
    ctx.fillStyle = '#cccccc'; ctx.fillRect(0,0,400,300);
    sk.photo = { dataUrl: c.toDataURL('image/jpeg', 0.8), width: 400, height: 300 };
    T.saveState();
""")
d.execute_script("const T=window.__test; T.ui.screen='sketch'; T.ui.sketchId=T.state.jobs[0].sketches[0].id; T.render();")
time.sleep(0.5)

# Test 1: simple last-expression
print("test1:", repr(d.execute_script("'hello';")))
# Test 2: last expression with side effects
print("test2:", repr(d.execute_script("""
window._x = 1;
'foo';
""")))
# Test 3: last expression with newlines
print("test3:", repr(d.execute_script("""
'foo';
'bar';
""")))
# Test 4: IIFE used as expression
print("test4:", repr(d.execute_script("(function(){ return 'foo'; })();")))
# Test 5: assignment as last expression
print("test5:", repr(d.execute_script("""
const x = 1;
x + 1;
""")))
d.quit()