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

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

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)]

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

        satellite.fill((255, 0, 0))
        fire.fill((250, 150, 0))
        smoke.fill((50, 50, 0))
        visualiser.rescale(1)

        def visualise(t, score, fuel_remaining, x, y, target_orbit_radius):
            if t % 40:
                return


            thrust = trail[-1]
            if thrust:
                screen.blit(fire, thrust)

            end_of_trail = trail.pop(0)
            if end_of_trail:
                screen.blit(smoke, end_of_trail)

            scale = visualiser.scale

            x = 250 + (x/(40000 * scale))
            y = 250 + (y/(40000 * scale))
            pos = (x,y)

            trail.append(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)

            screen.blit(satellite, pos)
            pygame.display.flip()

        visualiser.visualise = visualise

    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))
        pygame.draw.circle(visualiser.screen, (0,0,255),
            (250, 250),
            earth_size)

    def log(visualiser, t, score, fuel_remaining, x, y, target_orbit_radius):
        radius = sqrt((x*x) + (y*y))
        miss = sqrt(abs(target_orbit_radius - radius))
        if miss < 100:
            print miss
            print "%s : [ Fuel: %s | X: %s | Y: %s | target = %s ]" % ( t, fuel_remaining, x, y, target_orbit_radius )
