# THIS FILE IS A PART OF VCStudio
# PYTHON 3

import os

# GTK module ( Graphical interface or Gimp ToolKit
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
from gi.repository import GLib
from gi.repository import Gdk
import cairo

# Own modules
from settings import settings
from settings import talk
from project_manager import pm_project

from studio import analytics
from studio import story
from studio import studio_gtk
from studio import studio_dialogs

#UI modules
from UI import UI_elements
from UI import UI_color


def layer(win):
    
    # Making the layer
    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, win.current['w'],
                                                      win.current['h'])
    layer = cairo.Context(surface)
    
    
    #text setting
    layer.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)  
   
    # Reloads images every time the window size changes

    try:
        
        if (win.current['w'] != win.previous['w']):
            UI_elements.reload_images(win, force = True, only_cell = 1)
    except:
        print(f'Ignore: {layer} seems to be broken ):')

    # Internet things
    def do():
        
        # I used to have a specific UI instance for the help layer here. But
        # it proved to be too hard to maintain. So I'm changing it to a different
        # dialog. I'm not going to delete the help layer it self. For curious 
        # poeple.
        
        # win.url = "help_layer"
        
        # The following commands are the replacement. So if you want to see how
        # it used to look. Comment those. So not to launch both in the same time.
        
        def after(win, var):
           pass
        
        studio_dialogs.help(win, "help", after, SEARCH=talk.text("documentation_project_manager"))
    
    UI_elements.roundrect(layer, win,
        win.current['w'] - 50,
        5, 
        40,
        40,
        10,
        do,
        "question",
        talk.text("pm_internet_tooltip"),
        url="project_manager")
    
    # Update
    def do():
        win.url = "update_layer"

    UI_elements.roundrect(layer, win,
        win.current['w'] - 100,
        5, 
        40,
        40,
        10,
        do,
        "update",
        talk.text("update"),
        url="project_manager")

    # This will open and close the sidebar
    if 'main_sidebar_open_close' not in win.current:
        win.current['main_sidebar_open_close'] = False
    def do():
        win.current['main_sidebar_open_close'] = not win.current['main_sidebar_open_close']

    UI_elements.roundrect(layer, win,
        win.current['w'] - 50,
        win.current['h'] - 50, 
        40,
        40,
        10,
        do,
        "question",
        talk.text("sidebar_left"),
        url="project_manager") 
    
    # I gonna draw a little thingy for if a new update is available
    try:
        if win.update["count"]:
            count = str(win.update["count"])
            
            UI_color.set(layer, win, "node_background")
            UI_elements.roundrect(layer, win,
                30,
                win.current["h"]-100, 
                len(count)*12+6,
                25,
                5)
            layer.fill()
            UI_color.set(layer, win, "text_normal")
            layer.set_font_size(20)
            layer.move_to(33,win.current["h"]-80)
            layer.show_text(count)
            
    except:
        pass
    
    # Settings
    def do():
        win.url = "settings_layer"
    
    UI_elements.roundrect(layer, win,
        win.current['w'] - 150,
        5, 
        40,
        40,
        10,
        do,
        "settings",
        talk.text("Settings"),
        url="project_manager")
    
    # Now let's make previews of projects. I think each one will be it's own
    # layer thingy. Just so I could draw things inside them.
    
    # Clipping so it wont draw beyond the frame
    if win.current['main_sidebar_open_close']:
        io_close = 100
    else:
        io_close = 0
    UI_elements.roundrect(layer, win,
        0,
        50, 
        win.current["w"] - io_close,
        win.current["h"] - 50,
        30,
        fill=False)
    layer.clip()
    
#    UI_color.set(layer, win, "dark_overdrop")
#    layer.rectangle(0,0,9000,2000)
#    layer.fill()

    
    # Setting up scroll for Projects
    if "pm_scroll" not in win.current:
        win.current["pm_scroll"] = 0.0

    if "pm_main" not in win.scroll:
        win.scroll["pm_main"] = -400

    if 'game_selected' not in win.current:
        win.current['game_selected'] = 'fridaynightfunkin.png'
    project = win.current['game_selected']
    
    # sizes of banner
    x = 10
    y = 60 + win.scroll['pm_main']
    width = win.current['w']
    height = 300 

    # banner's shadow
    UI_color.set(layer, win, "shadow")
    UI_elements.roundrect(layer, win,
        x + 5,
        y + 5, 
        width,
        height,
        30,
        fill=True)
    
    # creates a blank layer
    node_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    node = cairo.Context(node_surface)  

    # it adds a transparancy mask to the node 
    UI_elements.roundrect(node, win,
            0,
            0, 
            width,
            height,
            30,
            fill=False)
    node.clip()
    
    # background colour for smaller images
    UI_color.set(node, win, "banner_white")
    UI_elements.roundrect(node, win,
        0,
        0, 
        width,
        height,
        30,
        fill=True)

    # draws images
    UI_elements.image(node, win, 'game_previews/' + project,
         0 , 0, width, height, cell = 1)

    # Drawing the Node on the main layer.
    layer.set_source_surface(node_surface, x,y)
    layer.paint()
    
    # Setting up tilling
    tileY = 400 
    tileX = 0

    width = 350
    height = 197

    # calculates where is the middle of the screen based upon the tiles
    tmp_foo = int((win.current["w"] - io_close) / (width + 10)) # of the tile
    offset = (win.current['w'] / 2) - (tmp_foo * (width + 10) / 2)
    tileX = offset

    # temp look into a folder instead the LBRY protocol and tiling (^:3:^)
    games = os.listdir('game_previews')
    for num, project in enumerate(games): 
        
        if tileX > (win.current["w"] - io_close) - 391:
            tileY += 197 + 10
            tileX = offset
        project_node(layer, win, tileX, 60 + tileY + win.scroll["pm_main"], project)
        
        tileX += 360
    
    UI_elements.scroll_area(layer, win, "pm_main", 
        0,
        50, 
        win.current["w"] - io_close,
        win.current["h"] - 50,
        tileY + 340,
        bar = False,
        mmb = True,
        strenght = 200,
        url="project_manager"
        ) 
    
    return surface

def project_node(layer, win, x, y, project):
    
    # This function will draw a project to a given place.
    node_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, win.current['w'],
                                                           win.current['h'])
    node = cairo.Context(node_surface)
    node.select_font_face("Monospace", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL)   
    
    # sizes of width and height

    width = 350
    height = 197

    # shadow
    UI_color.set(node, win, "shadow")
    UI_elements.roundrect(node, win,
        x + 5,
        y + 5, 
        width,
        height,
        20,
        fill=True)

    # mouseover
    if x + width  > win.current['mx'] > x and y + height > win.current['my'] > y:
        x -= 5
        y -= 5

    # Before we gonna do clip. Let's put here the logic of the node.
    def do():
        print(project)
        UI_elements.animate('scroll_pm_main', win, v1 = win.scroll["pm_main"], v2 = 0, time = 10, force = True)
        win.scroll["pm_main"] = 0
        win.current['game_selected'] = project

    Legacytip = ""
    nameonly = project[project.rfind("/")+1:]
    timefraction = 0.0
    projectfraction = 0.0
            
    node.set_line_width(10)
    UI_elements.roundrect(node, win,
        x + 5,
        y + 5, 
        width - 10,
        height - 10,
        20 + 5,
        button = do,
        fill = False,
        tip = project+Legacytip,
        url = "project_manager")
   # node.stroke()
   

    # This next roundrect will both be the backdrop of the node and both will 
    # clip the node content. All folowing graphics will be drawn clipped to the
    # current roundrect. 
    
    UI_color.set(node, win, "node_background")
    UI_elements.roundrect(node, win,
        x,
        y, 
        width,
        height,
        20)
    
    # Clip
    UI_elements.roundrect(node, win,
        x,
        y, 
        width,
        height,
        20,
        fill=False)
    node.clip()
    
    # this finds images and crops them to the right size
    UI_elements.image(node, win, 'game_previews/'+ project,
       x, y, width, height)
    
    # Drawing the Node on the main layer.
    layer.set_source_surface(node_surface, 0,0)
    layer.paint()
