"""
Interpreter avatar interpreter
"""
import logging
import queue

from direct.showbase.ShowBase import ShowBase
from direct.actor.Actor import Actor
from direct.task import Task
from panda3d.core import PointLight
from pandac.PandaModules import WindowProperties

import simplepbr

from .config import CFG, path2unix


# sign request queue
_queue = queue.Queue(CFG.SIGN_QUEUE_SIZE)


class ArtificialInterpreter(ShowBase):
    """Renderer application object
    """
    def __init__(self):
        super().__init__()
        simplepbr.init()
        # window props
        props = WindowProperties()
        props.setTitle('Pose estimation and tracking for sign language recognition')
        self.win.requestProperties(props)

        self.queue = _queue
        # disable mouse camera control and set static camera position and rotation
        self.disableMouse()
        self.camera.setPos(0, -2, 1.65)
        self.camera.setHpr(0, -10, 0)
        # set ambient light
        light = PointLight('light')
        intensity = 25
        light.setColor((intensity, intensity, intensity, 1))
        light.setAttenuation((0, 0, 1))
        self.light = self.render.attachNewNode(light)
        self.light.setPos(0, -2.5, 2)
        self.render.setLight(self.light)
        # import avatar actor object
        self.actor = Actor(path2unix(CFG.MODEL_PATH))
        self.actor.reparentTo(self.render)
        # save animation controllers
        self.anim_controlers = {anim: self.actor.getAnimControl(anim) for anim in self.actor.getAnimNames()}
        list(self.anim_controlers.values())[0].play(0, 1)
        # add queue management to task manager
        self.taskMgr.add(self.queue_task, 'queue_task')

    def sign(self, word, language):
        """Perform signing animation based on the word and target language

        Args:
            word (str): sign word in english
            language (str): target language code
        """
        action_name = f'{word}-{language}'
        if action_name in self.actor.getAnimNames():
            logging.debug(f'Playing {word} in {language} language')
            self.actor.play(action_name)
        else:
            logging.warning(f'No animation found for \"{word}\" in {language} - Skipping')
    
    def queue_task(self, task):
        """Manage sign request queue, if interpreter is already signing, don't load next request and wait for it to finish
        """
        # if queue is empty - continue
        if self.queue.empty():
            return Task.cont
        # check if any animation is playing, if so continue
        for ctrl in self.anim_controlers.values():
            if ctrl.isPlaying():
                return Task.cont
        # play animation from queue
        word, language = self.queue.get()
        self.sign(word, language)
        return Task.cont
