import webview as wb
import sys
import os
import json


class Api:

  def __init__(self) -> None:
    self.path=os.path.split(os.path.abspath(sys.argv[0]))[0]

  def load_plan(self):
    print("button click.")
    print(self.path)
    result = wnd.create_file_dialog(dialog_type=wb.OPEN_DIALOG,directory=self.path,
                                    file_types=('JSON (*.json)', 'All files (*.*)'))
    print(result)
    if(result is None):
      return None
    if(len(result)>0):
      with open(result[0],encoding="utf-8") as f:
        return json.loads(f.read())
    return None

  def save_plan(slef,plan:dict):
    path=os.path.split(os.path.abspath(sys.argv[0]))[0]
    file_name=wnd.create_file_dialog(dialog_type=wb.SAVE_DIALOG,directory=path,save_filename=plan["PlanBrief"],
                           file_types=('JSON (*.json)', 'All files (*.*)'))
    print(file_name)
    if(file_name is None):
      return
    json_str=json.dumps(plan, sort_keys=True, indent=4, separators=(',', ': '),ensure_ascii=False)
    with open(file_name,"w+",encoding="utf-8") as f:
      f.write(json_str)

wnd=wb.create_window("My Web App",url="layui/index.html",js_api=Api(),width=1200)
wb.start(http_server=True,debug=True)
