"""Record and replay .nts macros with cancellable waits."""
from pathlib import Path
import threading, math
from lyntin import manager, exported, event
from lyntin.modules import modutils
ROOT=Path(__file__).resolve().parents[2]/"scripts"
class ScriptManager(manager.Manager):
  def __init__(self):
    self._name=""
    self._script=False
    self._file=None
    self._cancel=threading.Event()
    self._worker=None
  def path(self,name):
    path=(ROOT/(name+".nts")).resolve()
    if path.parent != ROOT.resolve(): raise ValueError("Nom de macro invalide")
    return path
  def start(self,name):
    if self._name or self._script: return "Une macro est déjà en cours."
    self._file=self.path(name).open("w",encoding="utf-8")
    self._name=name
    exported.hook_register("from_user_hook",self.read,5)
    return "Enregistrement de la macro : "+name
  def read(self,args):
    data=args["data"]
    if not data.startswith("#stop_script"):
      self._file.write(data+";sec:0.8\n")
      self._file.flush()
  def stop(self,name):
    if not self._name: return "Aucun enregistrement en cours."
    if name != self._name: return "La macro en cours s'appelle : "+self._name
    exported.hook_unregister("from_user_hook",self.read)
    self._file.close()
    self._file=None
    self._name=""
    return "Fin de l'enregistrement."
  def execute(self,name):
    if self._name or self._script: return "Une macro est déjà en cours."
    lines=self.path(name).read_text(encoding="utf-8").splitlines()
    steps=[]
    for line in lines:
      if not line.strip(): continue
      cmd,seconds=line.rsplit(";sec:",1)
      seconds=float(seconds)
      if not math.isfinite(seconds) or seconds<0: raise ValueError("Délai invalide")
      steps.append((cmd,seconds))
    self._cancel.clear()
    self._script=True
    ses=exported.get_current_session()
    def run():
      try:
        for cmd,seconds in steps:
          if self._cancel.is_set(): break
          event.InputEvent(cmd,internal=1,ses=ses).enqueue()
          if self._cancel.wait(seconds): break
      finally:
        self._script=False
        exported.write_message("Macro arrêtée." if self._cancel.is_set() else "Fin de la macro.")
    self._worker=threading.Thread(target=run,name="NTLyntinMacro",daemon=True)
    self._worker.start()
    return "Lecture de la macro : "+name
  def cancel(self,*args):
    self._cancel.set()
    return "Arrêt demandé."
  def shutdown(self,args):
    self.cancel()
    if self._name: self.stop(self._name)
def execute_script_cmd(ses,args,input): exported.write_message(sm.execute(args["script"]))
def start_script_cmd(ses,args,input): exported.write_message(sm.start(args["script"]))
def stop_script_cmd(ses,args,input): exported.write_message(sm.stop(args["script"]))
def unexecute_script_cmd(ses,args,input): exported.write_message(sm.cancel())
commands_dict={"execute_script":(execute_script_cmd,"script"),"start_script":(start_script_cmd,"script"),
 "stop_script":(stop_script_cmd,"script"),"unexecute_script":(unexecute_script_cmd,"script=")}
sm=None
def load():
  global sm
  sm=ScriptManager()
  exported.add_manager("script",sm)
  modutils.load_commands(commands_dict)
  exported.hook_register("shutdown_hook",sm.shutdown)
def unload():
  sm.shutdown({})
  exported.hook_unregister("shutdown_hook",sm.shutdown)
  modutils.unload_commands(commands_dict)
  exported.remove_manager("script")
