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)

DRAW_JS = """
(function(){
  const canvas = document.getElementById('sketchCanvas');
  canvas.setPointerCapture = function(){};
  canvas.releasePointerCapture = function(){};
  canvas.hasPointerCapture = function(){ return false; };
  const rect = canvas.getBoundingClientRect();
  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;
  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';
})();
"""
d.execute_script(DRAW_JS)
time.sleep(0.5)
# Close the auto-opened dimension sheet.
d.execute_script('document.querySelector(".sheet-minimal [data-action=closesheet]").click()')
time.sleep(0.4)

# Set value
print("setLineValue:", d.execute_script("""
const T = window.__test;
const sk = T.state.jobs[0].sketches[0];
const line = sk.lines[0];
T.setLineValue(line, 100.125);
T.saveState();
return JSON.stringify(line);
"""))

# Try GET_LINE_VALUE_JS
GET_LINE_VALUE_JS = """
(function(){
  const T = window.__test;
  const sk = T.state.jobs[0].sketches[0];
  const line = sk.lines[0];
  const v = line;
  const f = v.feet || 0, i = v.inches || 0, s = v.sixteenths || 0;
  let inches = i, sixteenths = s;
  if (sixteenths >= 16) { inches += Math.floor(sixteenths / 16); sixteenths = sixteenths % 16; }
  const fracMap = {0:'', 1:'1/16', 2:'1/8', 3:'3/16', 4:'1/4', 5:'5/16', 6:'3/8', 7:'7/16', 8:'1/2', 9:'9/16', 10:'5/8', 11:'11/16', 12:'3/4', 13:'13/16', 14:'7/8', 15:'15/16'};
  const frac = fracMap[sixteenths] || '';
  const inchStr = frac ? (inches + ' ' + frac) : String(inches);
  if (f > 0) return f + "'-" + inchStr + '"';
  return inchStr + '"';
})();
"""
print("GET_LINE_VALUE_JS:", repr(d.execute_script(GET_LINE_VALUE_JS)))
d.quit()