'''
Canvas stress
=============

This example tests the performance of our Graphics engine by drawing large
numbers of small sqaures. You should see a black canvas with buttons and a
label at the bottom. Pressing the buttons adds small colored squares to the
canvas.

'''
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.spinner import Spinner
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.splitter import Splitter
from kivy.uix.image import Image
from kivy.app import App
from kivy.clock import Clock
from kivy.graphics import Color, Rectangle
from kivy.uix.behaviors import ToggleButtonBehavior
from kivy.uix.popup import Popup

from random import random as r
from functools import partial
from os import path, walk
from agent_dir import *

import agent_list
import env_list


def gen_popup(title, text, dismiss=True):
    """Generate a popup."""
    popup_layout = BoxLayout(orientation='vertical')
    content = Button(text='Close', size_hint=(1, .3))
    popup_layout.add_widget(Label(text=text))
    popup = Popup(title=title,
                  content=popup_layout)
    if dismiss:
        popup_layout.add_widget(content)
        content.bind(on_press=popup.dismiss)
    return popup


class Renderer(Widget):

    def __init__(self):
        super(Renderer, self).__init__()
        self._imgs = {}
        self._tile_size = (0, 0)

        self.add_images_from_folder(self._imgs, './img')
        self.add_images_from_folder(self._imgs, './agent_dir/img')

    def add_images_from_folder(self, container, folder):
        images = {}

        for root, dirs, files in walk(path.abspath(folder)):
            for file_ in files:
                name, ext = path.splitext(path.basename(file_))
                if ext == '.png':
                    images[name] = Image(source=path.join(root, file_))

        container.update(images)

    def real_pos(self, x, y):
        return (self.x + x * self._tile_size[0],
                self.y + y * self._tile_size[1])

    def set_tile_size(self, env):
        if env is not None:
            n_x, n_y = max([thing.location for thing in env.things])
            tile_x = self.width / float(n_x + 1)
            tile_y = self.height / float(n_y + 1)
            self._tile_size = (tile_x, tile_y)

    def clear(self):
        self.canvas.clear()

    def draw(self, env):
        self.clear()

        if env is not None:
            walls = []
            dirts = []
            cleans = []
            agents = []

            for thing in env.things:
                if isinstance(thing, Wall):
                    walls.append(thing)
                elif isinstance(thing, Dirt):
                    dirts.append(thing)
                elif isinstance(thing, Clean):
                    cleans.append(thing)
                elif isinstance(thing, Agent):
                    agents.append(thing)