import numpy as np
from collections import deque
from PIL import Image
import gym
from gym import spaces


class NoopResetEnv(gym.Wrapper):
    def __init__(self, env, noop_max=30):
        """Sample initial states by taking random number of no-ops on reset.
        No-op is assumed to be action 0.
        """
        gym.Wrapper.__init__(self, env)
        self.noop_max = noop_max
        self.override_num_noops = None
        assert env.unwrapped.get_action_meanings()[0] == 'NOOP'

    def _reset(self):
        """ Do no-op action for a number of steps in [1, noop_max]."""
        self.env.reset()
        if self.override_num_noops is not None:
            noops = self.override_num_noops
        else:
            noops = self.unwrapped.np_random.randint(1, self.noop_max + 1) #pylint: disable=E1101
        assert noops > 0
        obs = None
        for _ in range(noops):
            obs, _, done, _ = self.env.step(0)
            if done:
                obs = self.env.reset()
        return obs

class FireResetEnv(gym.Wrapper):
    def __init__(self, env):
        """Take action on reset for environments that are fixed until firing."""
        gym.Wrapper.__init__(self, env)
        assert env.unwrapped.get_action_meanings()[1] == 'FIRE'
        assert len(env.unwrapped.get_action_meanings()) >= 3

    def _reset(self):
        self.env.reset()
        obs, _, done, _ = self.env.step(1)
        if done:
            self.env.reset()
        obs, _, done, _ = self.env.step(2)
        if done:
            self.env.reset()
        return obs

class EpisodicLifeEnv(gym.Wrapper):
    def __init__(self, env):
        """Make end-of-life == end-of-episode, but only reset on true game over.
        Done by DeepMind for the DQN and co. since it helps value estimation.
        """
        gym.Wrapper.__init__(self, env)
        self.lives = 0
        self.was_real_done  = True

    def _step(self, action):
        obs, reward, done, info = self.env.step(action)
        self.was_real_done = done
        # check current lives, make loss of life terminal,
        # then update lives to handle bonus lives
        lives = self.env.unwrapped.ale.lives()
        if lives < self.lives and lives > 0:
            # for Qbert somtimes we stay in lives == 0 condtion for a few frames
            # so its important to keep lives > 0, so that we only reset once
            # the environment advertises done.
            done = True
        self.lives = lives
        return obs, reward, done, info

    def _reset(self):
        """Reset only when lives are exhausted.
        This way all states are still reachable even though lives are episodic,
        and the learner need not know about any of this behind-the-scenes.
        """
        if self.was_real_done:
            obs = self.env.reset()
        else:
            # no-op step to advance from terminal/lost life state
            obs, _, _, _ = self.env.step(0)
        self.lives = self.env.unwrapped.ale.lives()
        return obs

class MaxAndSkipEnv(gym.Wrapper):
    def __init__(self, env, skip=4, curiosity_search=False, cs_weight=0, no_intrinsic=False):
        """Return only every `skip`-th frame"""
        gym.Wrapper.__init__(self, env)
        # most recent raw observations (for max pooling across time steps)
        self._obs_buffer = deque(maxlen=2)
        self._skip       = skip
        ### BEGIN CMS ADDITIONS 13/12/17
        self.curiositySearch = curiosity_search
        self.csWeight = cs_weight
        self.noIntrinsic = no_intrinsic
        ### END CMS ADDITIONS

    def _step(self, action):
        """Repeat action, sum reward, and max over last observations."""
        total_reward = 0.0
        done = None
        for _ in range(self._skip):
            obs, reward, done, info = self.env.step(action)
            self._obs_buffer.append(obs)
            if (self.curiositySearch and not self.noIntrinsic):
                if self.csWeight < 0:
                    total_reward += reward + info["intrinsic"]
                else:
                    if self.csWeight > 1:
                        self.csWeight = 1.0
                    reward = np.sign(reward) # pre-clip reward
                    total_reward += (self.csWeight * info["intrinsic"]) + ((1 - self.csWeight) * reward)
            else:
                total_reward += reward
            if done:
                break
        max_frame = np.max(np.stack(self._obs_buffer), axis=0)

        return max_frame, total_reward, done, info

    def _reset(self):
        """Clear past frame buffer and init. to first obs. from inner env."""
        self._obs_buffer.clear()
        obs = self.env.reset()
        self._obs_buffer.append(obs)
        return obs

class ClipRewardEnv(gym.RewardWrapper):
    def __init__(self, env):
        gym.RewardWrapper.__init__(self, env)

    def _reward(self, reward):
        """Bin reward to {+1, 0, -1} by its sign."""
        return np.sign(reward)

class WarpFrame(gym.ObservationWrapper):
    def __init__(self, env, curiosity_search, random_noise, no_grid):
        """Warp frames to 84x84 as done in the Nature paper and later work."""
        gym.ObservationWrapper.__init__(self, env)
        self.res = 84
        ### BEGIN CMS ADDITIONS, 10/01/17
        self.curiositySearch = curiosity_search
        self.randomNoise = random_noise
        self.noGrid = no_grid
        ### END CMS ADDITIONS
        self.testIndex = 0
        if not self.noGrid and (self.curiositySearch or self.randomNoise):
            self.observation_space = spaces.Box(low=0, high=255, shape=(self.res, self.res, 2))
        else:
            self.observation_space = spaces.Box(low=0, high=255, shape=(self.res, self.res, 1)) # the original code

    def _observation(self, obs, info=None):
        frame = np.dot(obs.astype('float32'), np.array([0.299, 0.587, 0.114], 'float32'))
        #Image.fromarray(frame).resize((self.res, self.res)).convert('RGB').save("/project/EvolvingAI/cstanto3/test/i" + str(self.testIndex) + ".png")
        frame = np.array(Image.fromarray(frame).resize((self.res, self.res),
            resample=Image.BILINEAR), dtype=np.uint8)
        if ((not self.curiositySearch or self.noGrid) and not self.randomNoise):
            return frame.reshape((self.res, self.res, 1))

        ### BEGIN RANDOM NOISE (ADDED BY CMS 26/09/17)
        if (self.randomNoise):
            frame = frame.reshape((self.res, self.res, 1))
            randomNoise = np.random.randint(low=0, high=2, size=(self.res, self.res, 1), dtype=np.uint8) * 255
            return np.concatenate((frame, randomNoise), 2)
        ### END RANDOM NOISE

        ### BEGIN CURIOSITY SEARCH (ADDED BY CMS 10/01/17)
        if (not self.noGrid and self.curiositySearch and self.env.unwrapped.curiositySearch):
            if (info is not None):
                csGrid = info["csGrid"]
            else:
                csGrid = self.env.unwrapped.getCurrCSGrid()
            #Image.fromarray(csGrid[:,:,0]).rotate(90).resize((self.res, self.res), resample=Image.NEAREST).convert('RGB').save("/project/EvolvingAI/cstanto3/test/im" + str(self.testIndex) + ".png")
            #self.testIndex = self.testIndex + 1
            csGrid = np.array(Image.fromarray(csGrid[:,:,0]).rotate(90).resize((self.res, self.res), resample=Image.NEAREST), dtype=np.uint8)
            frame = frame.reshape((self.res, self.res, 1))
            csGrid = csGrid.reshape((self.res, self.res, 1))
            return np.concatenate((frame, csGrid), 2)
        ### END CURIOSITY SEARCH

        raise RuntimeError("Unspecified warp options.")

class FrameStack(gym.Wrapper):
    def __init__(self, env, k):
        """Buffer observations and stack across channels (last axis)."""
        gym.Wrapper.__init__(self, env)
        self.k = k
        self.frames = deque([], maxlen=k)
        shp = env.observation_space.shape
        assert shp[2] == 1  # can only stack 1-channel frames
        self.observation_space = spaces.Box(low=0, high=255, shape=(shp[0], shp[1], k))

    def _reset(self):
        """Clear buffer and re-fill by duplicating the first observation."""
        ob = self.env.reset()
        for _ in range(self.k): self.frames.append(ob)
        return self._observation()

    def _step(self, action):
        ob, reward, done, info = self.env.step(action)
        self.frames.append(ob)
        return self._observation(), reward, done, info

    def _observation(self):
        assert len(self.frames) == self.k
        return np.concatenate(self.frames, axis=2)

def wrap_deepmind(env, episode_life=True, clip_rewards=True, curiosity_search=False, random_noise=False, cs_weight=-1, no_grid=False, no_intrinsic=False):
    """Configure environment for DeepMind-style Atari.

    Note: this does not include frame stacking!"""
    assert 'NoFrameskip' in env.spec.id  # required for DeepMind-style skip
    if episode_life:
        env = EpisodicLifeEnv(env)
    env = NoopResetEnv(env, noop_max=30)
    env = MaxAndSkipEnv(env, skip=4, curiosity_search=curiosity_search, cs_weight=cs_weight, no_intrinsic=no_intrinsic)
    if 'FIRE' in env.unwrapped.get_action_meanings():
        env = FireResetEnv(env)
    env = WarpFrame(env, curiosity_search, random_noise, no_grid)
    if clip_rewards:
        env = ClipRewardEnv(env)
    return env
