# -*- coding: utf-8 -*-
# #############################################################################
# Copyright (C) 2022 manatlan manatlan[at]gmail(dot)com
#
# MIT licence
#
# https://github.com/manatlan/htag
# #############################################################################
from .. import Tag
from ..render import HRenderer

"""
With this runner ... you could use guy.run(..), guy.runCef( ...) and guy.serve(...) methods (and auto reloader too)
(and deliver APK on android, see guy's docs)

LIMITATION : But multi client doesn't work using guy.serve().
(because HRenderer can manage only one instance at once)
(to handle multiple, you should modify this class to handle multiple HRenderer)
"""
try:
    import guy
except ImportError:
    import sys
    print("You should install 'guy' for this htag runner")
    sys.exit(-1)

class GuyApp(guy.Guy):
    """ Open the rendering in a GUY instance
    Interaction with buil-in guy websockets !
    """

    def __init__(self,tag: Tag):
        js = """
async function interact( o ) {
    action( await self.interact(o["id"], o["method"], o["args"], o["kargs"]) );
}

guy.init( start );
"""
        if type(tag.statics)==list:
            tag.statics.append(Tag.script(_src="guy.js"))   # add the js script "guy.js" (autogenerated by guy)
        else:
            tag.statics=[tag.statics, Tag.script(_src="guy.js")]

        self.renderer=HRenderer(tag, js, self.exit)

        super().__init__()

    async def interact(self,tagid:str,method:str,args,kargs): # guy binded method
        """ guy exposed method to interact"""
        return await self.renderer.interact(tagid,method,args,kargs)

    def render(self,path=None):
        """ Override guy.render(...) to produce a default rendering """
        return str(self.renderer)
