"""
Copyright (C) 2008  Matthew and Joey Marshall <joey@arcticpaint.com>

See main.py for full notice.
"""
from __future__ import division
import rabbyt
import snowui
import random
from pyglet.window import mouse, key
from pyglet.text import HTMLLabel

from gamelib.cable import Cable
from gamelib.station import Station, StationPlaceholder
from gamelib.ui import UI
from gamelib.world import Island

import simplejson

class EditorUI(UI):
    def setup(self):
        UI.setup(self)

        build_button = snowui.widget_setting(snowui.Button,
                texture="button.png", y=20, bounds="rect",
                callback=self.set_mode,
                default_color=(0,0.7,0,1), hover_color=(0,1,0,1))

        self.add(build_button(icon="icon_decors.png", x=20*3+56*2,
                cb_data="decors"))

        self.add(build_button(icon="icon_islands.png", x=20*4+56*3,
                cb_data="islands"))

        self.add(build_button(icon="icon_sp.png", x=20*5+56*4,
                cb_data="station_places"))

        self.add(build_button(icon="icon_save.png", x=20*7+56*6,
                callback=self.save))


    def save(self):
        out = simplejson.dumps(self.map.data, sort_keys=False, indent=4)
        fp = open("/usr/local/share/gondola/maps/%s.json"%self.map.mapname, "w")
        fp.write(out)
        fp.close()
        print "saved"


    def handle_mouse_press(self, x, y, button, modifiers):
        if self.mode == "decors":
            x,y = self.view.to_world_pixels((x,y))
            if button == mouse.LEFT:
                name = random.choice(["rock", "plant"])
                name += str(random.randint(0,1))
                self.map.data["decors"].append({"name":name, "xy":(x,y)})
                s = rabbyt.Sprite("decors/"+name+".png", xy=(x,y))
                self.world.decors.append(s)
                self.world.renderables["decors"].append(s)
            elif button == mouse.MIDDLE:
                for d in self.collide_objects((x,y),
                        self.world.decors):
                    idx = self.world.decors.index(d)
                    self.world.decors.remove(d)
                    self.world.renderables["decors"].remove(d)
                    self.map.data["decors"].pop(idx)
            else:
                self.mode = None
        elif self.mode == "islands":
            x,y = self.view.to_world_pixels((x,y))
            if button == mouse.LEFT:
                i = random.randint(1,5)
                rot = random.randint(0,359)
                island = Island(self.world, (x,y), i)
                island.rot = rot
                self.map.data["islands"].append({"id":i, "xy":(x,y), "rot":rot})
            elif button == mouse.MIDDLE:
                for d in self.collide_objects((x,y),
                        self.world.islands):
                    idx = self.world.islands.index(d)
                    self.world.islands.remove(d)
                    self.world.renderables["islands"].remove(d)
                    self.map.data["islands"].pop(idx)
            else:
                self.mode = None
        elif self.mode == "station_places":
            x,y = self.view.to_world_pixels((x,y))
            if button == mouse.LEFT:
                StationPlaceholder(self.world, (x,y))
                self.map.data["station_placeholders"].append({"xy":(x,y)})
            elif button == mouse.MIDDLE:
                for d in self.collide_objects((x,y),
                        self.world.station_placeholders):
                    idx = self.world.station_placeholders.index(d)
                    self.world.station_placeholders.remove(d)
                    self.map.data["station_placeholders"].pop(idx)
            else:
                self.mode = None

        else:
            UI.handle_mouse_press(self, x, y, button, modifiers)


    def scroll_screen(self, x, y):
        self.scroll_speed = 10
        xy = self.view.xy
        if x < 10:
            self.view.x -= self.scroll_speed
        elif x > self.window.width-10:
            self.view.x += self.scroll_speed
        if y < 4:
            self.view.y -= self.scroll_speed
        elif y > self.window.height - 10:
            self.view.y += self.scroll_speed

        k = self.keyboard
        if k[key.RIGHT] or k[key.D]:
            self.view.x += self.scroll_speed
        if k[key.LEFT] or k[key.A]:
            self.view.x -= self.scroll_speed
        if k[key.UP] or k[key.W]:
            self.view.y += self.scroll_speed
        if k[key.DOWN] or k[key.S]:
            self.view.y -= self.scroll_speed


    def render(self):
        self.scroll_screen(*self.mouse_xy)

        if self.mode == "build" or self.mode == "station_places":
            for sp in self.world.station_placeholders:
                if not sp.station:
                    sp.render()
                    idx = self.world.station_placeholders.index(sp)
                    l = HTMLLabel(str(idx), x=sp.x, y=sp.y)
                    l.draw()
        if self.selected:
            self.selection_sprite.xy = self.selected.xy
            self.selection_sprite.render()

        self.gui_view.set_viewport()
        snowui.GUI.render(self)
