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)

print("current screen:", d.execute_script("return window.__test.ui.screen"))
print("sketch id:", d.execute_script("return window.__test.ui.sketchId"))
print("has canvas:", d.execute_script("return !!document.getElementById('sketchCanvas')"))
print("line count before draw:", d.execute_script("return window.__test.state.jobs[0].sketches[0].lines.length"))

# Try drawing
result = d.execute_script("""
(function(){
  const canvas = document.getElementById('sketchCanvas');
  canvas.setPointerCapture = function(){};
  canvas.releasePointerCapture = function(){};
  canvas.hasPointerCapture = function(){ return false; };
  const rect = canvas.getBoundingClientRect();
  console.log('canvas rect:', JSON.stringify(rect));
  const opts = { bubbles: true, cancelable: true, pointerId: 1, pointerType: 'touch', isPrimary: true };
  const sx = rect.left + rect.width*0.3, sy = rect.top + rect.height*0.4;
  const ex = rect.left + rect.width*0.7, ey = rect.top + rect.height*0.6;
  console.log('draw from', sx, sy, 'to', ex, ey);
  canvas.dispatchEvent(new PointerEvent('pointerdown', Object.assign({}, opts, {clientX: sx, clientY: sy})));
  for (let i = 1; i <= 5; i++) canvas.dispatchEvent(new PointerEvent('pointermove', Object.assign({}, opts, {clientX: sx+(ex-sx)*i/5, clientY: sy+(ey-sy)*i/5})));
  canvas.dispatchEvent(new PointerEvent('pointerup', Object.assign({}, opts, {clientX: ex, clientY: ey})));
  return 'drawn';
})();
""")
print("draw result:", result)
time.sleep(0.5)
print("line count after draw:", d.execute_script("return window.__test.state.jobs[0].sketches[0].lines.length"))
print("draft:", d.execute_script("return JSON.stringify(window.__test.ui.sketchDraft)"))
print("pinModal:", d.execute_script("return JSON.stringify(window.__test.ui.pinModal)"))
d.quit()