# THIS FILE IS A PART OF VCStudio
# PYTHON 3

import os
import datetime
import json
from subprocess import *

# GTK module ( Graphical interface
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 settings import fileformats
from settings import oscalls
from project_manager import pm_project

#UI modules
from UI import UI_elements
from UI import UI_color
from UI import UI_math

# Studio
from studio import studio_dialogs
from studio import analytics
from studio import story

def layer(win, call):
    
    ##########################################################################
    
    # This file will select a VSE blend file. And create ones when needed.
    # I'm making it as a dialog (see: studio/studio_dialogs.py ) because I
    # want to be able to use this UI in various places in VCStudio.
    
    # The launching of the file will be done by a host Layer. 
    
    ##########################################################################
    
    
    # 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)
    
    UI_color.set(layer, win, "dark_overdrop")
    layer.rectangle(
        0,
        0,
        win.current["w"],
        win.current["h"],
        )
    layer.fill()
    
    
    
    UI_color.set(layer, win, "node_background")
    UI_elements.roundrect(layer, win, 
        win.current["w"]/2-250,
        100,
        500,
        win.current["h"]-200,
        10)
    
    
    
    # Exit button
    def do():
        win.current["calls"][call]["var"] = False 
        
        
    UI_elements.roundrect(layer, win, 
        win.current["w"]/2+210,
        win.current["h"]-140,
        40,
        40,
        10,
        button=do,
        icon="cancel",
        tip=talk.text("cancel"))
    
    
    x = win.current["w"]/2-250 + 10
    y = 170
    width = 500 - 20
    height = win.current["h"]-270
    
    # Search
    
    UI_elements.image(layer, win, "settings/themes/"\
        +win.settings["Theme"]+"/icons/search.png", 
        x+width/4,
        y-50, 
        40,
        40)
    
    UI_elements.text(layer, win, "in_vses",
        x+width/4+50,
        y-50,
        width/2-50,
        40)
    
    # Clip
    
    UI_elements.roundrect(layer, win, 
        x,
        y,
        width,
        height-60,
        10,
        fill=False)
    layer.clip()
    
    clip = [
        x,
        y,
        width,
        height-60]
    
    # Little testing thing. Make it True to see where it's clipping.
    if False:
        # Background
        UI_color.set(layer, win, "dark_overdrop")
        layer.rectangle(x,y,width, height)
        layer.fill()
    
    
    # Setting up the scroll
    if "vse" not in win.scroll:
        win.scroll["vse"] = 0
    
    current_Y = 0
    
    # There is not going to be any launch buttons. Basically you click on a 
    # file in the list and it's launched. ( Or out_putted into parent function )
    # And since the contents of those blend files are not model based. Let's not
    # draw tiles of squares, but rather a simple list would be fine.
    
    # I think something like
    
    #####################################################
    #                                                   #
    #                  [____SEARCH____]                 #
    #                                                   #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #             []   NAME_OF_FILE.BLEND               #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                                   #
    #                                               X   #
    #####################################################
    
    # Of course It's going to look better in the end. I'm not great with ASCII
    # art. And of course to add a blend file you will look for it in a search
    # and it will give you to make one or copy one. Like usual.
    
    blends = []
    for blend in os.listdir(win.project+"/rnd"):
        if blend.endswith(".blend"):
            blends.append(blend)
    
    # I just did this because there could not be a file to begin with. And I
    # want to make one if such doesn't exists.
    
    if not blends:
        newname = "sequence.blend"
        
        oscalls.copy_file(
            win,
            os.getcwd()+"/new_file/seq.blend",
            "/rnd/",
            newname)
    
    # Okay since now we have our file let's list them. Or it. Yeah.
    
    newcreate = win.text["in_vses"]["text"].replace("/","_").replace(" ", "_")\
    .replace('"',"_").replace("(","_").replace(")","_").replace("'","_")\
    .replace("[","_").replace("]","_").replace("{","_").replace("}","_")
    
    for blend in blends:
        
        # Search
        if newcreate and newcreate.lower() not in blend.lower():
            continue
        
        # LAUNCH BUTTON
        def do():
            win.current["calls"][call]["var"] = "/rnd/"+blend
                
        UI_elements.roundrect(layer, win, 
            x,
            y+current_Y + win.scroll["vse"],
            width,
            40,
            10,
            button=do)
        
        # ICON
        UI_elements.image(layer, win, "settings/themes/"\
            +win.settings["Theme"]+"/icons/vse.png", 
            x+5,
            y+current_Y + win.scroll["vse"], 
            40,
            40)
        
        # NAME
        UI_color.set(layer, win, "text_normal")
        layer.set_font_size(20)
        layer.move_to(x+50,
                y+current_Y + win.scroll["vse"]+30)
        layer.show_text(blend)
        
        current_Y = current_Y + 50
    
    # Now let's make the 2 adding buttons and to hell with it.
    
    if newcreate and newcreate not in blends:
        
        if not newcreate.endswith(".blend"):
            newcreate = newcreate + ".blend"
        
        # NEW FILE
        
        def do():
            oscalls.copy_file(
                win,
                os.getcwd()+"/new_file/seq.blend",
                "/rnd/",
                newcreate)
            win.text["in_vses"]["text"] = ""
            
        UI_elements.roundrect(layer, win, 
            x,
            y+current_Y + win.scroll["vse"],
            width,
            40,
            10,
            button=do)
        
        UI_color.set(layer, win, "progress_background")
        UI_elements.roundrect(layer, win, 
            x,
            y+current_Y + win.scroll["vse"],
            width,
            40,
            10,
            fill=False)
        layer.stroke()
        
        # ICON
        UI_elements.image(layer, win, "settings/themes/"\
            +win.settings["Theme"]+"/icons/new_file.png", 
            x+5,
            y+current_Y + win.scroll["vse"], 
            40,
            40)
        
        # NAME
        UI_color.set(layer, win, "text_normal")
        layer.set_font_size(20)
        layer.move_to(x+50,
                y+current_Y + win.scroll["vse"]+30)
        layer.show_text(newcreate)
        
        current_Y = current_Y + 50
        
        
        # COPY FILE
        
        def do():
            def after(win, var):
                if var and var.endswith(".blend"):
                    oscalls.copy_file(
                        win,
                        var,
                        "/rnd/",
                        newcreate)
                    win.text["in_vses"]["text"] = ""
            
            studio_dialogs.file_select(win, "seq_blends", after, force=True, 
                    IMAGE=False, BLEND=True, VIDEO=False, FILE=False, CHR=False, VEH=False, 
                    LOC=False, OBJ=False, RND=True, FOLDER=False)
            
        UI_elements.roundrect(layer, win, 
            x,
            y+current_Y + win.scroll["vse"],
            width,
            40,
            10,
            button=do)
        
        UI_color.set(layer, win, "progress_background")
        UI_elements.roundrect(layer, win, 
            x,
            y+current_Y + win.scroll["vse"],
            width,
            40,
            10,
            fill=False)
        layer.stroke()
        
        # ICON
        UI_elements.image(layer, win, "settings/themes/"\
            +win.settings["Theme"]+"/icons/copy_file.png", 
            x+5,
            y+current_Y + win.scroll["vse"], 
            40,
            40)
        
        # NAME
        UI_color.set(layer, win, "text_normal")
        layer.set_font_size(20)
        layer.move_to(x+50,
                y+current_Y + win.scroll["vse"]+30)
        layer.show_text(newcreate)
        
        current_Y = current_Y + 50
        
        
    ###########################
        
    UI_elements.scroll_area(layer, win, "vse", 
        x,
        y,
        width,
        height-60,
        current_Y,
        bar=True,
        mmb=True,
        url="vse"
    )
    
    
    return surface