# 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

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)

  
    
    
    ui.color(game, layer, "#FFFFFF")
    ui.text(game, layer, "Settings",
            int(game.current["w"]/2), 5,
            align="center")

    def do():
        game.scene = "main_menu"
    
    ui.button(game, layer,
              5, 
              5 , 
              int(game.current["w"] / 3 ) - 30 ,
              13,
              menu="settings",
              string="< Back",
              func=do)

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

    max_width = min(200, int(game.current["w"]/2))
    putx = int(game.current["w"]/2-max_width/2)

    # Fancy frame

    ui.color(game, layer, "green")
    layer.set_line_width(2)
    layer.move_to(putx-5,25)
    layer.line_to(putx, 20)
    layer.line_to(putx+max_width+3, 20)
    layer.line_to(putx+max_width+3, game.current["h"]-25)
    layer.line_to(putx+max_width-2, game.current["h"]-15)
    layer.line_to(putx-5, game.current["h"]-15)
    
    layer.close_path()
    layer.stroke_preserve()
    ui.color(game, layer, "dark_blue")
    layer.fill_preserve()
    
    current_Y = 0
    #layer.rectangle(4,20,
    #            game.current["w"]-10,
    #            game.current["h"]-25)
    layer.clip()


    if "settings_graphics_active" not in game.current:
        game.current["settings_graphics_active"] = False

    wicon = "right"
    if game.current["settings_graphics_active"]:
        wicon = "down"
        
    def do():
        game.current["settings_graphics_active"] = not game.current["settings_graphics_active"]
        game.menus = {}
        
    ui.button(game, layer,
              putx,
              current_Y+25, 
              max_width ,
              13,
              menu="settings",
              scroll="settings",
              icon=wicon,
              string="Graphics",
              func=do)
    current_Y += 15

    if game.current["settings_graphics_active"]:
        # VIRTUAL PIXEL TO REAL PIXEL RATIO

        ui.color(game, layer, "#00FF00")
        ui.text(game, layer, "Size: ",
                putx,
                current_Y+28+game.scroll["settings"])

        def do():
            game.settings["pixels"] += 1
            save_settings(game)

        ui.button(game, layer,
                  putx+max_width-55,
                  current_Y+25, 
                  13,
                  13,
                  menu="settings",
                  scroll="settings",
                  string="+",
                  func=do)

        ui.color(game, layer, "#00FF00")
        ui.text(game, layer, str(game.settings["pixels"]),
                putx+max_width-30,
                current_Y+28+game.scroll["settings"])

        def do():
            game.settings["pixels"] -= 1
            if game.settings["pixels"] < 1:
                game.settings["pixels"] = 1
            save_settings(game)

        ui.button(game, layer,
                  putx+max_width-13,
                  current_Y+25, 
                  13,
                  13,
                  menu="settings",
                  scroll="settings",
                  string="-",
                  func=do)


        current_Y += 15

        # FULLSCREEN

        ficon = "fullscreen"
        if game.settings["fullscreen"]:
            ficon = "unfullscreen"

        def do():
            game.settings["fullscreen"] = not game.settings["fullscreen"]
            save_settings(game)

        ui.button(game, layer,
                  putx+10,
                  current_Y+25, 
                  max_width -10,
                  13,
                  menu="settings",
                  scroll="settings",
                  icon=ficon,
                  string="Fullscreen",
                  func=do)

        current_Y += 15

        # TESTING MODE

        dicon = "false"
        if game.current["testing"]:
            dicon = "true"

        def do():
            game.current["testing"] = not game.current["testing"]

        ui.button(game, layer,
                  putx+10,
                  current_Y+25, 
                  max_width -10,
                  13,
                  menu="settings",
                  scroll="settings",
                  icon=dicon,
                  string="Debug Mode",
                  func=do)


        current_Y += 15


        # Depth of Field option

        if game.settings["Blur"]:
            wicon = "true"
        else:
            wicon = "false"

        def do():
            game.settings["Blur"] = not game.settings["Blur"]
            save_settings(game)

        ui.button(game, layer,
                  putx+10,
                  current_Y+25, 
                  max_width -10,
                  13,
                  menu="settings",
                  scroll="settings",
                  icon=wicon,
                  string="Depth of Field",
                  func=do)
        current_Y += 15

        if game.settings["Blur"]:

            if game.settings["NN-Upscaler-Blur"]:
                wicon = "true"
            else:
                wicon = "false"

            def do():
                game.settings["NN-Upscaler-Blur"] = not game.settings["NN-Upscaler-Blur"]
                save_settings(game)

            ui.button(game, layer,
                 putx+20,
                 current_Y+25, 
                 max_width -20,
                 13,
                 menu="settings",
                 scroll="settings",
                 icon=wicon,
                 string="Pixelate",
                 func=do)
            current_Y += 15


            # Depth of Field downscale NN option

            if game.settings["NN-Downscaler-Blur"]:
                wicon = "true"
            else:
                wicon = "false"

            def do():
                game.settings["NN-Downscaler-Blur"] = not game.settings["NN-Downscaler-Blur"]
                save_settings(game)

            ui.button(game, layer,
                  putx+20,
                  current_Y+25, 
                  max_width -20,
                  13,
                  menu="settings",
                  scroll="settings",
                  icon=wicon,
                  string="Pixelate+",
                  func=do)
            current_Y += 15


        current_Y += 15

    # WOLDS
    
    if "settings_world_active" not in game.current:
        game.current["settings_world_active"] = False

    wicon = "right"
    if game.current["settings_world_active"]:
        wicon = "down"
        
    def do():
        game.current["settings_world_active"] = not game.current["settings_world_active"]
        game.menus = {}
        
    ui.button(game, layer,
              putx,
              current_Y+25, 
              max_width ,
              13,
              menu="settings",
              scroll="settings",
              icon=wicon,
              string="World: "+game.worlds[game.settings["world"]]["title"],
              func=do)
    current_Y += 15

    # List of worlds
    if game.current["settings_world_active"]:

        current_Y += 15

        for world in game.worlds:
            def do():
                game.settings["world"] = world
                game.current["settings_world_active"] = False
                game.menus = {}
                save_settings(game)

            wicon = "radio_false"
            if game.settings["world"] == world:
                wicon = "radio_true"
                
            ui.button(game, layer,
                      putx+10,
                      current_Y+25, 
                      max_width - 25 ,
                      13,
                      menu="settings",
                      scroll="settings",
                      icon=wicon,
                      string=str(game.worlds[world]["title"]),
                      func=do)

            # Editor
            def do():
                game.settings["world"] = world
                game.current["settings_world_active"] = False
                game.menus = {}
                game.chunks = [[],{}]
                save_settings(game)
                
                game.scene = "editor"
        
            ui.button(game, layer,
                      putx+max_width-13,
                      current_Y+25, 
                      13,
                      13,
                      menu="settings",
                      scroll="settings",
                      icon="edit",
                      func=do)
            
            current_Y += 15

        # Autosave option
        current_Y += 15
        
        if game.settings["autosave"]:
            wicon = "true"
        else:
            wicon = "false"

        def do():
            game.settings["autosave"] = not game.settings["autosave"]
            save_settings(game)

        ui.button(game, layer,
                  putx+10,
                  current_Y+25, 
                  max_width -10,
                  13,
                  menu="settings",
                  scroll="settings",
                  icon=wicon,
                  string="Autosave",
                  func=do)
        current_Y += 15

        
    ui.scroll_area(game, layer, "settings", 5,20,
                   game.current["w"]-10,
                   game.current["h"]-50,
                   current_Y)


    # Navigating the menus
    ui.button_navigate(game, "settings")
    
            
    return surface

def update_worlds(game):

    """This function updates the selection of playable worlds."""

    game.worlds = {}
    for world in os.listdir(os.getcwd()+"/assets/worlds"):
        try:
            with open("assets/worlds/"+world+"/world.json") as f:
                metadata = json.load(f)
        except:
            metadata = {"title":world}

        game.worlds[world] = metadata

def get_settings_folder(folder="ineh/"):

    try:
        data_dir = os.environ["XDG_DATA_HOME"] + "/" + folder
    except:
        data_dir = os.path.expanduser("~/.local/share/"+folder)

    try:
        os.makedirs(data_dir)
    except:
        pass

    return data_dir
        
def save_settings(game):

    """This function saves the settings"""

    with open(get_settings_folder()+"config.json", 'w') as f:
        json.dump(game.settings, f, indent=4, sort_keys=True)

def load_settings(game):

    """This function loads settings, or creates the settings
       from defautls"""

    defaults = {
        "pixels":4,    # How big are pixels on the screen
        "fullscreen":False, # Whether the games is fullscreen
        "world":"ImNotEvenHuman", # What wold you are playing
        "autosave":True,
        "undo_history_buffer":10,
        "Blur":False,
        "NN-Downscaler-Blur":False, # Downscaler for the Depth of field effect when downscaling sprites
        "NN-Upscaler-Blur":False # Upscaler for the Depth of field effect when upscaling back sprites
        }
    try:
        with open(get_settings_folder()+"config.json") as f:
            game.settings = json.load(f)
    except:
        game.settings = defaults
    
    # Adds new missing attributes
    for i in defaults:
        if i not in game.settings:
            game.settings[i] = defaults[i]


    # print(game.settings)
            
