import pickle
import sys

from pygsear.Game import Game
from pygsear.Event import KEY_Event
from pygsear.Drawable import Drawable, Circle, RotatedImage
from pygsear.Widget import Dialog_LineInput
from pygsear.locals import RED, PI
from pygsear import conf

import pygame
from pygame.locals import *

import Architecture
from Architecture import Cell, Wall, Door, Level

TS = Architecture.TS

from wix import Party, WixGame


class WixEditorParty(Party):
    def make_move(self, direction=None):
        if direction is None:
            direction = self.facing

        if self.level is not None:
            block = None
            if block is None or block.passable or (block.door is not None and block.door.passable):
                move_func = getattr(self, '_move_%s' % direction)
                coord = self.coord[:]
                crect = pygame.Rect(self.crect)
                try:
                    move_func()
                    self.level.cells[tuple(self.coord)]
                    print 'moved', direction, 'to', self.coord
                except KeyError:
                    x, y = self.coord
                    c = Cell(x, y)
                    #items = {}
                    #items = {'west': 'Wall', 'south': 'Wall', 'east': 'Wall', 'north': 'Wall'}
                    #c.add_items(**items)
                    self.level.add_cell(c)
            else:
                print 'blocked', direction

        self.update_vis()



class WixEditor(WixGame):
    def initialize(self):
        self.set_background(color=(125, 125, 175))

        #self.load_level(cells=cells)
        #self.load_level('seed_level.pickle')
        self.level = Level()
        self.level.add_cell(Cell(0, 0))
        self.level.set_mode_topdown()

        self.events.add(KEY_Event(key=(K_w, K_a, K_d, K_s), on_press=self.nudge_map))

        self.party = WixEditorParty()
        self.party.enter_level(self.level)
        self.level.layer.sprites.add(self.party.vis)
        self.events.add(KEY_Event(key=K_LEFT, on_press=self.party.turn_left))
        self.events.add(KEY_Event(key=K_RIGHT, on_press=self.party.turn_right))
        self.events.add(KEY_Event(key=K_UP, on_press=self.party.move_forward))

        self.level.set_mode_topdown_edit()
        self.level.add_cell(Cell(0, 0))
        #self.level.set_mode_topdown_cansee(self.party)
        self.level.draw()

        self.events.add(KEY_Event(key=K_F1, on_press=self.do_load_level))
        self.events.add(KEY_Event(key=K_F2, on_press=self.save_level))

        self.events.add(KEY_Event(key=K_x, on_press=self.del_cell))
        self.events.add(KEY_Event(key=K_F7, on_press=self.outer_walls))
        self.events.add(KEY_Event(key=K_F8, on_press=self.outer_walls_double))
        self.events.add(KEY_Event(key=K_z, on_press=self.add_wall))
        self.events.add(KEY_Event(key=K_c, on_press=self.add_door))
        self.events.add(KEY_Event(key=K_h, on_press=self.make_hidden))

        self.events.add(KEY_Event(key=K_u, on_press=self.add_stairs, direction='up'))


    def do_load_level(self, ev=None):
        WixGame.do_load_level(self)
        self.level.set_mode_topdown_full()
        self.level.draw()

    def save_level(self, ev=None):
        print 'saving'
        if not hasattr(self, 'level_filename'):
            filename = ''
        else:
            filename = self.level_filename
        filename = Dialog_LineInput(message="Save File Name?", default=filename).modal()
        if filename:
            self.level.save(filename)
            self.level_filename = filename
            print 'done saving', filename
        else:
            print 'save aborted'

    def add_wall(self, ev=None):
        cells = self.level.cells
        coord = tuple(self.party.coord)
        cell = cells[coord]
        facing = self.party.facing

        #cell.clear_topdown()
        if not cell.items.has_key(facing):
            cell.add_items(**{facing: 'Wall'})
        else:
            cell.add_items(**{facing: None})
        self.level.draw()

    def add_door(self, ev=None):
        cells = self.level.cells
        coord = tuple(self.party.coord)
        cell = cells[coord]
        facing = self.party.facing

        #cell.clear_topdown()
        if not cell.items.has_key(facing):
            pass
        elif cell.items[facing] == 'Wall':
            cell.add_items(**{facing: 'Door'})
        elif cell.items[facing] == 'Door':
            cell.add_items(**{facing: 'Wall'})
        self.level.draw()

    def make_hidden(self, ev=None):
        cells = self.level.cells
        coord = tuple(self.party.coord)
        cell = cells[coord]
        facing = self.party.facing

        #cell.clear_topdown()
        if not cell.items.has_key(facing):
            pass
        elif cell.items[facing] == 'Door':
            cell.add_items(**{facing: 'HDoor'})
        elif cell.items[facing] == 'Wall':
            cell.add_items(**{facing: 'HWall'})
        self.level.draw()

    def del_cell(self, ev=None):
        coord = tuple(self.party.coord)
        try:
            cell = self.level.cells[coord]
            cell.clear_topdown()
            del(self.level.cells[coord])
        except KeyError:
            pass

    def outer_walls(self, ev=None):
        cells = self.level.cells
        for coord in cells:
            cell = cells[coord]
            x, y = cell.coord
            walls = {'north': (0, 1), 'east': (1, 0), 'south': (0, -1), 'west': (-1, 0)}
            opp = {'north': 'south', 'east': 'west', 'south': 'north', 'west': 'east'}
            for side in walls:
                if cell.items.has_key(side):
                    continue
                dx, dy = walls[side]
                k = (x+dx, y+dy)
                if not cells.has_key(k):
                    #cell.clear_topdown_full()
                    cell.add_items(**{side: 'Wall'})
        self.level.draw()

    def outer_walls_double(self, ev=None):
        cells = self.level.cells
        for coord in cells:
            print coord
            cell = cells[coord]
            x, y = cell.coord
            walls = {'north': (0, 1), 'east': (1, 0), 'south': (0, -1), 'west': (-1, 0)}
            opp = {'north': 'south', 'east': 'west', 'south': 'north', 'west': 'east'}
            for side in walls:
                print side,
                if cell.items.has_key(side):
                    print 'present'
                    continue
                dx, dy = walls[side]
                k = (x+dx, y+dy)
                #print k
                if not cells.has_key(k) or cells[k].items.has_key(opp[side]):
                    print 'add'
                    #cell.clear_topdown_full()
                    cell.add_items(**{side: 'Wall'})
        self.level.draw()

    def add_stairs(self, ev=None, direction=None):
        print 'add stairs', direction
        cells = self.level.cells
        coord = tuple(self.party.coord)
        cell = cells[coord]

        if not cell.items.has_key('Stairs'):
            cell.add_items(**{'Stairs': (direction, 'where?')})
        else:
            cell.add_items(**{'Stairs': None})

        self.level.draw()



def main():
    g = WixEditor()

    if len(sys.argv) > 1 and sys.argv[1]:
        g.load_level(sys.argv[1])
        g.level.set_mode_topdown()
        g.party.enter_level(g.level)
        g.level.layer.sprites.add(g.party.vis)
        g.level.set_mode_topdown_cansee(g.party)
        g.level.draw()

    g.mainloop()



if __name__ == '__main__':
    main()
