# -*- coding: utf-8 -*-

# ============== pygame visualiser

def load_image(fullname, colorkey=None):
    import os

    image = pygame.image.load(fullname)
    image = image.convert()
    if colorkey is not None:
        if colorkey is -1:
            colorkey = image.get_at((0,0))
        image.set_colorkey(colorkey, RLEACCEL)
    return image, image.get_rect()
    
import pygame
from math import sqrt
class Visualiser(object):
    def __init__(visualiser, size):
        pygame.init()

        screen = pygame.display.set_mode(size)
        surface = pygame.Surface(size).convert()
        satellite = pygame.Surface((3, 3)).convert()
        fire = pygame.Surface((3, 3)).convert()
        smoke = pygame.Surface((3, 3)).convert()
        trail = [None for i in xrange(10)]
#        earth_pic, rect = load_image("./earth-small.bmp")

        visualiser.__dict__.update(
            size = size,
            screen = screen,
            surface = surface,
            satellite = satellite,
            fire = fire,
            smoke = smoke,
            trail = trail,
 #           earth_pic = earth_pic,
        )

        satellite.fill((255, 0, 0))
        fire.fill((250, 150, 0))
        smoke.fill((50, 50, 0))
        visualiser.rescale(1)
        
    def point(visualiser, colour):
        point = pygame.Surface((3, 3)).convert()
        point.fill(colour)
        return point

    def plot_point(visualiser, t, x, y, satellite):
        if t % 40: return
        scale = visualiser.scale
        x = 250 + (x/(40000 * scale))
        y = 250 + (y/(40000 * scale))
        pos = (x,y)
        visualiser.screen.blit(satellite, pos)
        
        max_x, max_y = visualiser.size
        if x<0 or x> max_x or y<0 or y> max_y:
            visualiser.rescale(visualiser.scale * 2)        
        trail = visualiser.trail
        visualiser.trail.append(pos)
        thrust = trail[-1]
        if thrust:
            visualiser.screen.blit(visualiser.fire, thrust)
   
        end_of_trail = trail.pop(0)
        if end_of_trail:
            visualiser.screen.blit(visualiser.smoke, end_of_trail)

    def visualise(visualiser, t, score, fuel_remaining, x, y, *args):
        if t % 40:
            return


        visualiser.plot_point(t, x, y, visualiser.satellite)

        pygame.display.flip()

    def rescale(visualiser, scale):
        visualiser.scale = scale
        earth_size = 160/scale
        x,y = visualiser.size
        visualiser.x_offset = x/(2*scale)
        visualiser.y_offset = y/(2*scale)
        visualiser.screen.fill((0, 0, 0))
        visualiser.trail = [None for i in xrange(10)]
        
       # visualiser.screen.blit(visualiser.earth_pic, pos)
        
        pygame.draw.circle(visualiser.screen, (0,0,255),
            (250, 250),
            earth_size)

    def log(visualiser, t, score, fuel_remaining, x, y, *args):
        radius = sqrt((x*x) + (y*y))
        print "%s : [ Fuel: %s | X: %s | Y: %s ]" % ( t, fuel_remaining, x, y )
