# THIS IS A SOURCE CODE FILE FROM I'M NOT EVEN HUMAN THE GAME.
# IT COULD BE USED IN A DIFFERENT PIECE OF SOFTWARE ( LIKE A
# DIFFERENT GAME ), BUT IT WAS ORIGINALLY WRITTEN FOR I'M NOT
# EVEN HUMAN THE GAME.

# THE DEVELOPERS OF THE GAME ARE : (C) J.Y.AMIHUD, AYYZEE AND 
# OTHER CONTRIBUTORS. THIS AND OTHER FILES IN THIS GAME,
# UNLESS SPECIFICALLY NOTED, COULD BE USED UNDER THE TERMS OF
# GNU GENERAL PUBLIC LICENSE VERSION 3 OR ANY LATER VERSION.

import os
import json

# GTK module ( Graphical interface
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import cairo

from modules import ui
from modules import world

def layer(game):
    
    # Setting up a cairo layer
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32,
                                 game.current['w'],
                                 game.current['h'])
    layer = cairo.Context(surface)
    layer.set_antialias(cairo.ANTIALIAS_NONE)


    def do():
        game.scene = "settings"
    
    ui.button(game, layer,
              5, 
              5 , 
              int(game.current["w"] / 3 ) - 30 ,
              13,
              menu="editor",
              string="< Back",
              func=do)
    
    ui.color(game, layer, "#FFFFFF")
    ui.text(game, layer, game.worlds[game.settings["world"]]["title"],
            int(game.current["w"]/2), 5,
            align="center")

    # THE WORLD VIEW
    world.draw(game, layer, int(game.current["w"] / 3), 20,
               int(game.current["w"]/3*2),
               game.current["h"]-50, grid=True)

    # BOTTOM TOOL BAR

    # Heigh setting ( Layer )
    def do():
        game.current["camera"][2] += 1
           
    ui.button(game, layer,
              2,
              game.current["h"]-30, 
              13 ,
              13 ,
              menu="editor",
              icon="up",
              func=do)
    def do():
        game.current["camera"][2] -= 1
    ui.button(game, layer,
              2,
              game.current["h"]-15, 
              13 ,
              13 ,
              menu="editor",
              icon="down",
              func=do)
    ui.color(game, layer, "#00FF00")
    ui.text(game, layer, "Height",
            17,game.current["h"]-30)
    ui.text(game, layer, str(game.current["camera"][2]),
            17,game.current["h"]-15)
    
    # Brush size
    def do():
        game.current["editor_brush"] += 1
           
    ui.button(game, layer,
              65,
              game.current["h"]-30, 
              13 ,
              13 ,
              menu="editor",
              icon="up",
              func=do)
    def do():
        game.current["editor_brush"] -= 1
        if game.current["editor_brush"] < 1:
            game.current["editor_brush"] = 1
    ui.button(game, layer,
              65,
              game.current["h"]-15, 
              13 ,
              13 ,
              menu="editor",
              icon="down",
              func=do)
    ui.color(game, layer, "#00FF00")
    ui.text(game, layer, "Brush Size",
            82,game.current["h"]-30)
    ui.text(game, layer, str(game.current["editor_brush"]),
            82,game.current["h"]-15)
    
    # Save button
    def do():
        world.save_chunk(game)

    ui.button(game, layer,
              game.current["w"]-15,
              game.current["h"]-15, 
              13 ,
              13 ,
              menu="editor",
              icon="floppy",
              func=do)


    # Save with hotkey
    if game.current["ctrlDown"] and 115 in game.current["keys"]:
        do()
        game.current["keys"].remove(115)

    #####################################
    #        TREE VIEW SELECTOR         #
    #####################################

    # The next section will implement a tree view
    # to select various editable assets.

    # Setting up the scroller
    if "editor" not in game.scroll:
        game.scroll["editor"] = 0

    current_Y = 0
    layer.rectangle(1, 19,
                    int(game.current["w"]/3)-3,
                    game.current["h"]-70)

    layer.clip() # From here, Draw only inside the mask layer.rectangle(1, 19...

    if "editor_chooser" not in game.current:
        game.current["editor_chooser"] = {}
    
    for types in game.elements:

        if "type_"+types not in game.current["editor_chooser"]:
            game.current["editor_chooser"]["type_"+types] = False
        
        def do():
            
            game.menus = {}
            game.current["editor_chooser"]["type_"+types] = not game.current["editor_chooser"]["type_"+types]

        if game.current["editor_chooser"]["type_"+types]:
            wicon = "down"
        else:
            wicon = "right"
        ui.button(game, layer,
                      2,
                      current_Y+20, 
                      int(game.current["w"]/3)-4 ,
                      13 ,
                      menu="editor",
                      scroll="editor",
                      icon=wicon,
                      string=types,
                      func=do,
                      borders=False)
        current_Y += 13

        if game.current["editor_chooser"]["type_"+types]:

            current_Y += 5
            
            for asset in game.elements[types]:


                if "asset_"+asset not in game.current["editor_chooser"]:
                    game.current["editor_chooser"]["asset_"+asset] = False
                
                try:
                    assetname = game.images["assets/elements/"+types+"/"+asset]["title"]
                except:
                    assetname = asset

                try:
                    assetColor = game.images["assets/elements/"+types+"/"+asset]["menu_color"]
                except Exception as e:
                    assetColor = "#000000"
                    print("EEEEEEEEE: ",e)
                
                
                def do():
                    
                    game.menus = {}
                    game.current["editor_chooser"]["asset_"+asset] = not game.current["editor_chooser"]["asset_"+asset]

                if game.current["editor_chooser"]["asset_"+asset]:
                    wicon = "down"
                else:
                    wicon = "right"
                
                ui.color(game, layer, assetColor)
                layer.rectangle(7, current_Y+20+game.scroll["editor"], int(game.current["w"]/3)-9 , 13)
                layer.fill()
                if isBright(assetColor):
                    colorToSet = "#222222"
                else:
                    colorToSet = "#FFFFFF"

                ui.button(game, layer,
                      7,
                      current_Y+20, 
                      int(game.current["w"]/3)-9 ,
                      13 ,
                      menu="editor",
                      scroll="editor",
                      icon=wicon,
                      string=assetname,
                      func=do,
                      borders=False,
                      btnTxtColor=colorToSet)
                current_Y += 13

                if game.current["editor_chooser"]["asset_"+asset]:

                    current_Y += 5
                    
                    for n, version in enumerate(game.elements[types][asset]):

                        def do():
                            game.current["editor_selection"][0] = types
                            game.current["editor_selection"][1] = asset
                            game.current["editor_selection"][2] = n

                        if game.current["editor_selection"][2]  == n\
                        and game.current["editor_selection"][1] == asset\
                        and game.current["editor_selection"][0] == types:
                            wicon = "radio_true"
                        else:
                            wicon = "radio_false"
                        
                        try:
                            versionColor = version["menu_color"]
                        except:
                            versionColor = assetColor

                        ui.color(game, layer, versionColor)
                        layer.rectangle(10, current_Y+20+game.scroll["editor"], int(game.current["w"]/3)-12 , 13)
                        layer.fill()
                        if isBright(versionColor):
                            colorToSet = "#222222"
                        else:
                            colorToSet = "#DDDDDD"

                        ui.button(game, layer,
                                  10,
                                  current_Y+20, 
                                  int(game.current["w"]/3)-12 ,
                                  13 ,
                                  menu="editor",
                                  scroll="editor",
                                  icon=wicon,
                                  string=str(version["title"]),
                                  func=do,
                                  borders=False,
                                  btnTxtColor=colorToSet)

                        # Mouse over the block
                        if int(game.current["mx"]) in range(10, int(game.current["w"]/3)+6 )\
                        and int(game.current["my"]) in range(int(current_Y+20+game.scroll["editor"]), int(current_Y+20+game.scroll["editor"]+13)):
                            ui.image(game, layer,
                                     game.current["mx"]-20,
                                     game.current["my"]-20,
                                     "assets/elements/"+types+"/"+asset, version["title"], offset=True)
                            
                        
                        current_Y += 13
                    current_Y += 5
            current_Y += 5

                    
    ui.scroll_area(game, layer, "editor", 1, 19,
                    int(game.current["w"]/3)-3,
                    game.current["h"]-70,
                   current_Y)
    
    # Navigating the menus
    ui.button_navigate(game, "editor")
    

    # Check chunks in memory
    if 32 in game.current["keys"]:
        print(game.chunks)
        print()
        game.current["keys"].remove(32)

    return surface

def isBright(code):
    new_c = []
    for c in range(3):
        ind = int((len(code)-1)/3)
        new_c.append( int(code[ind*c+1:ind*c+ind+1], 16)/255 )
    avg = sum(new_c)/len(new_c)

    if avg > 0.5:
        return True
    else:
        return False