"""Screen Capture."""

# AUTOGENERATED! DO NOT EDIT! File to edit: ../nbs/01_capture.ipynb.

# %% auto #0
__all__ = ['setup_share', 'start_share', 'capture_screen', 'capture_tool']

# %% ../nbs/01_capture.ipynb #9b3dd8ad
from .core import *
from fastcore.all import *
from fasthtml.common import Div,Script
from httpx import post as xpost
from importlib import resources
from io import BytesIO

import base64,json,time,PIL.Image,asyncio

# %% ../nbs/01_capture.ipynb #4591f71d
def setup_share():
    "Setup screen sharing"
    txt = (resources.files('dialoghelper')/'screenshot.js').read_text()
    iife(txt)
    time.sleep(0.3)

# %% ../nbs/01_capture.ipynb #7f0cbd49
def start_share(): trigger_now('shareScreen')

# %% ../nbs/01_capture.ipynb #5c81465d
async def _capture_screen(timeout=15):
    d = await event_get_a('captureScreen', timeout)
    if 'img_data' in d: return d.img_data
    else: raise Exception(f'Capture failed: {d.error}')

async def capture_screen(timeout=15):
    "Capture the screen as a PIL image."
    res = await _capture_screen()
    data = base64.b64decode(res.split(',')[1])
    return PIL.Image.open(BytesIO(data))

# %% ../nbs/01_capture.ipynb #c08b8ebc
@llmtool
async def capture_tool(timeout:int=15):
    "Capture the screen. Re-call this function to get the most recent screenshot, as needed. Use default timeout where possible"
    try: return await capture_screen(timeout)
    except Exception as e: return f'Capture failed: {e}'
