"""Dos metas explícitas en el Push-T de l01; uso secuencial en un proceso.

La escena presenta ambas metas. Cada instrucción selecciona la función de
éxito y el objetivo del experto, sin cambiar la imagen según la instrucción.
"""
import numpy as np
import p13_pusht as base

GOALS = {'azul': np.array([.19, .19, np.pi / 4]),
         'naranja': np.array([.32, .32, np.pi / 4])}
INSTRUCTIONS = {'azul': 'Empuja la T hasta la meta azul',
                'naranja': 'Empuja la T hasta la meta naranja'}

original = base.PUSHT_XML
xml = original.replace('body name="meta" pos="0.256 0.256 0.0005"',
                       'body name="meta" pos="0.19 0.19 0.0005"')
xml = xml.replace('rgba="0.35 0.75 0.45 1"', 'rgba="0.15 0.35 0.95 1"')
second = '''<body name="meta_naranja" pos="0.32 0.32 0.0005" euler="0 0 0.7853981634">
  <geom type="box" pos="0 0.015 0" size="0.06 0.015 0.0005" rgba="0.95 0.45 0.1 1" contype="0" conaffinity="0"/>
  <geom type="box" pos="0 0.075 0" size="0.015 0.045 0.0005" rgba="0.95 0.45 0.1 1" contype="0" conaffinity="0"/>
</body>'''
base.PUSHT_XML = xml.replace('</worldbody>', second + '</worldbody>')


class LanguageTask(base.TareaEmpujeT):
    def __init__(self, goal):
        if goal not in GOALS:
            raise ValueError('Meta desconocida')
        self.goal = goal
        super().__init__()
        self.nombre = 'empuje_t_' + goal
        self.texto = INSTRUCTIONS[goal]

    def reiniciar(self, seed):
        # Misma escena inicial para ambas instrucciones; excluye ambas metas.
        attempt = 0
        while True:
            base.META_T[:] = [.256, .256, np.pi / 4]
            super().reiniciar(seed + attempt * 1000003)
            if all(base.cobertura(self.env.pose(), goal) < .5 for goal in GOALS.values()):
                break
            attempt += 1
        base.META_T[:] = GOALS[self.goal]

    def actuar(self, action):
        base.META_T[:] = GOALS[self.goal]
        return super().actuar(action)

    def expert(self, seed):
        base.META_T[:] = GOALS[self.goal]
        e = base.ExpertoEmpujeT(self.env, semilla=seed)
        return lambda task, t: e() * 1000

    def coverage(self):
        return base.cobertura(self.env.pose(), GOALS[self.goal])
