# Swimmer-v2 env
# two objectives
# forward speed, energy efficiency

import numpy as np
from gym import utils
from gym.envs.mujoco import mujoco_env
from os import path
from moenvs.MujocoEnvs.constraint_env import CMOEnv

class SwimmerEnv(mujoco_env.MujocoEnv, utils.EzPickle):
    def __init__(self):     
        utils.EzPickle.__init__(self)
        mujoco_env.MujocoEnv.__init__(self, model_path = path.join(path.abspath(path.dirname(__file__)), "assets/swimmer.xml"), frame_skip = 4)
        self.obj_dim = 2
        self.action_space_type = "Continuous"
        self.reward_space = np.zeros((self.obj_dim,))
        
    def step(self, a):
        info = self._get_info()
        ctrl_cost_coeff = 0.15
        xposbefore = self.sim.data.qpos[0]
        # if isinstance(a, (np.ndarray)):
        #     a = a[0]
        a = np.clip(a, -1, 1)
        self.do_simulation(a, self.frame_skip)
        xposafter = self.sim.data.qpos[0]
        reward_fwd = (xposafter - xposbefore) / self.dt
        reward_ctrl = 0.3 - ctrl_cost_coeff * np.square(a).sum()
        ob = self._get_obs()

        x_velocity = (xposafter - xposbefore)/self.dt
        return ob, np.array([reward_fwd, reward_ctrl],dtype=np.float32), False, {'x_velocity': x_velocity, 'qpos': info[0], 'qvel': info[1]}

    def _get_obs(self):
        qpos = self.sim.data.qpos
        qvel = self.sim.data.qvel
        return np.concatenate([qpos.flat[2:], qvel.flat])

    def _get_info(self):
        qpos = self.sim.data.qpos
        qvel = self.sim.data.qvel
        return  np.concatenate([qpos.flat, qvel.flat])

    def reset_model(self):
        # self.set_state(
        #     self.init_qpos
        #     + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nq),
        #     self.init_qvel
        #     + self.np_random.uniform(low=-0.1, high=0.1, size=self.model.nv),
        # )
        c = 1e-3
        self.set_state(
            self.init_qpos + self.np_random.uniform(low=-c, high=c, size=self.model.nq),
            self.init_qvel + self.np_random.uniform(low=-c, high=c, size=self.model.nv)
        )
        return self._get_obs()

    

class CMOSwimmerEnv(SwimmerEnv, CMOEnv):
    def __init__(self):
        CMOEnv.__init__(self, min_episode_cost=0.0, max_episode_cost=200.0, velocity_threshold=0.04845) 
        SwimmerEnv.__init__(self,)
        self.obj_dim = 3
        self.reward_space = np.zeros((self.obj_dim,))

    def step(self, a):
        ob, rew, _, info = super().step(a)
        x_velocity = info['x_velocity']
        cost = float(x_velocity > self.velocity_threshold)
        rew_vec = np.append(rew, cost)
        rew = rew_vec if self.linear_preference is None else np.dot(rew_vec[:len(self.linear_preference)], self.linear_preference)
        info.update({'cost': cost, 'rew_vec': rew_vec[:-1]})
        return ob, rew, False, info
