import numpy as np
from gym import utils
from gym.envs.mujoco import mujoco_env

class AntEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(self, goal=30.0/180*np.pi, backward=False, task_one_hot_id=None):
        self._goal = goal
        self.backward = backward
        self.task_one_hot_id = task_one_hot_id
        mujoco_env.MujocoEnv.__init__(self, 'ant.xml', 5)
        utils.EzPickle.__init__(self)

    def step(self, a):
        # self.render()
        if not hasattr(self, "init_zpos"):
            self.init_zpos = self.sim.data.get_body_xpos('torso')[2]
        xy_position_before = self.get_body_com("torso")[:2].copy()
        self.do_simulation(a, self.frame_skip)
        xy_position_after = self.get_body_com("torso")[:2].copy()
        direct = (np.cos(self._goal), np.sin(self._goal))
        state = self.state_vector()

        xy_velocity = (xy_position_after - xy_position_before) / self.dt
        x_velocity, y_velocity = xy_velocity

        # xposbefore = self.get_body_com("torso")[0]
        # self.do_simulation(a, self.frame_skip)
        # xposafter = self.get_body_com("torso")[0]
        
        # forward_reward = (xposafter - xposbefore)/self.dt
        if not self.backward:
            forward_reward = x_velocity
        else:
            forward_reward = -x_velocity
        angle_reward = np.dot(np.array(xy_velocity), direct)
        ctrl_cost = .5 * np.square(a).sum()
        contact_cost = 0.5 * 1e-3 * np.sum(
            np.square(np.clip(self.sim.data.cfrc_ext, -1, 1)))
        survive_reward = 1.0
        reward_jump = 10.0*(state[2] - self.init_zpos)
        # reward = forward_reward - ctrl_cost - contact_cost + survive_reward
        reward = forward_reward - ctrl_cost - contact_cost + survive_reward
        notdone = np.isfinite(state).all() \
            and state[2] >= 0.2 and state[2] <= 1.0
        done = not notdone
        ob = self._get_obs()
        return ob, reward, done, dict(
            # reward_forward=forward_reward,
            reward_run=forward_reward,
            reward_jump=reward_jump,
            reward_angle=angle_reward,
            reward_ctrl=-ctrl_cost,
            reward_contact=-contact_cost,
            reward_survive=survive_reward)

    def _get_obs(self):
        if self.task_one_hot_id is not None:
            return np.concatenate([
                self.sim.data.qpos.flat[2:],
                self.sim.data.qvel.flat,
                np.clip(self.sim.data.cfrc_ext, -1, 1).flat,
                self.task_one_hot_id
                ])
        return np.concatenate([
            self.sim.data.qpos.flat[2:],
            self.sim.data.qvel.flat,
            np.clip(self.sim.data.cfrc_ext, -1, 1).flat,
        ])

    def reset_model(self):
        qpos = self.init_qpos + self.np_random.uniform(size=self.model.nq, low=-.1, high=.1)
        qvel = self.init_qvel + self.np_random.randn(self.model.nv) * .1
        self.set_state(qpos, qvel)
        self.init_zpos = self.sim.data.get_body_xpos('torso')[2]
        return self._get_obs()

    def viewer_setup(self):
        self.viewer.cam.distance = self.model.stat.extent * 0.5
