####################################
#                                  #
#        COPYRIGHT NOTICE          #
#                                  #
# This file is a part of Victori-  #
# ous Children Studio Organizer.   #
# Or simply VCStudio. Copyright    #
# of J.Y.Amihud. But don't be sad  #
# because I released the entire    #
# project under a GNU GPL license. #
# You may use Version 3 or later.  #
# See www.gnu.org/licenses if your #
# copy has no License file. Please #
# note. Ones I used the GPL v2 for #
# it. It's no longer the case.     #
#                                  #
####################################

import os
import urllib3

# 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 oscalls
from project_manager import pm_project
from project_manager import update_reader

#UI modules
from UI import UI_elements
from UI import UI_color
from UI import UI_Markdown


def layer(win):

    # Sometimes the user didn't want the software to check for updates automatically.
    # In this case we want to check for updates when he click on the update button.

    if not win.settings["check-for-updates"]:
        GLib.timeout_add(1 , update_reader.get_update_info, 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)
    
    UI_color.set(layer, win, "dark_overdrop")
    layer.rectangle(
        0,
        0,
        win.current["w"],
        win.current["h"],
        )
    layer.fill()
    
    # This is the Markdown UI object.

    UI_Markdown.draw(layer, win, "update_markdown", 
        20,
        100,
        win.current["w"]-40,
        win.current["h"]-200)
    
    UI_color.set(layer, win, "node_background")
    UI_elements.roundrect(layer, win, 
        50,
        win.current["h"]-80,
        win.current["w"]-100,
        50,
        10)
    
    # Exit button
    def do():
        win.url = "project_manager" 
        win.textactive = ""

    UI_elements.roundrect(layer, win, 
        55,
        win.current["h"]-75,
        40,
        40,
        10,
        button=do,
        icon="cancel",
        tip=talk.text("cancel"))

    # Setting to get all files. Sometimes you need a way to restore the entire
    # program. Or sometimes I make mistakes. And want give myself and others a
    # simple way to refresh the system. So here I gonna make a button that will
    # tell the updater to ignore the update version and download the whole 
    # package. All 300 something files. ( It's 2021/01 at the time. ) 
    
    # Also not so long ago I made Version naming mistakes. So some kind of way
    # to download versions should exist. Here we go.
    
    if "Update_all" not in win.settings:
        win.settings["Update_all"] = False
        settings.write("Update_all", False)
    
    if win.settings["Update_all"]:
        ic = "checked"
    else:
        ic = "unchecked"
    
    def do():
        win.settings["Update_all"] = not win.settings["Update_all"]
        settings.write("Update_all", win.settings["Update_all"])
        
        
    UI_elements.roundrect(layer, win, 
        110,
        win.current["h"]-75,
        250,
        40,
        10,
        button=do,
        icon=ic,
        tip=talk.text("update_all_tooltip"))

    UI_color.set(layer, win, "text_normal")
    layer.set_font_size(15)
    layer.move_to(
        150,
        win.current["h"]-50)
    layer.show_text(talk.text("update_all")+" "+str(len(win.update["get_all_files"]))+" "+talk.text("files"))

    # Install Updates button
    try:
        if win.update["count"] or win.settings["Update_all"]:
            def do():
                win.url = "install_updates"
                win.update["frame"] = win.current["frame"]
                
                
            UI_elements.roundrect(layer, win, 
                win.current["w"]-100,
                win.current["h"]-75,
                40,
                40,
                10,
                button=do,
                icon="ok",
                tip=talk.text("update_install"))
    except:
        pass

    # At the top of the Update window there is a selector bar to
    # select various versions. They will load the page into the
    # little browser below.

    # For this wee need to clip it.

    # Clipping everything
    UI_elements.roundrect(layer, win, 
        50,
        20,
        win.current["w"]-100,
        80,
        10,
        fill=False)
    layer.clip()
    
    clip = [
        50,
        20,
        win.current["w"]-100,
        80]
    
    # Setting up the scroll
    if "pm_update" not in win.scroll:
        win.scroll["pm_update"] = 0
    
    current_X = 0 # The max scroll value

    for version in win.update["versions"]:
        is_open = win.update["versions"][version]["open"]
        files   = win.update["versions"][version]["files"]
        link    = win.update["versions"][version]["link"]
        

        
        
        if version == win.version:
            UI_color.set(layer, win, "node_imagefile")
            sufix = talk.text("update_current")
        elif version < win.version:
            UI_color.set(layer, win, "node_badfile")
            sufix = talk.text("update_previous")
        elif version > win.version:
            UI_color.set(layer, win, "node_blendfile")
            sufix = talk.text("update_available")
        
        UI_elements.roundrect(layer, win, 
            current_X + 50 + win.scroll["pm_update"],
            20,
            300,
            40,
            10)
        
        UI_color.set(layer, win, "text_normal")
        layer.set_font_size(20)
        layer.move_to(current_X + 60 + win.scroll["pm_update"],
                      45)
        layer.show_text(str(version)+" "+sufix)
        
        def do():

            # We gonna attempt at previewing the update information in the window
            # and only if it's not going to work, we gonna launch the browser with
            # the link. Or do some weird. Like giving a generated page about the
            # stuff.

            openlink = "wiki/updates/"+str(version)+".md"

            if not os.path.exists(os.getcwd()+"/"+openlink):

                # In case the folder is not there yet
                
                try:
                    os.mkdir("wiki/updates")
                except:
                    pass

                # Now we are getting the file

                try:
                    http = urllib3.PoolManager()
                    resp = http.request('GET', "https://notabug.org/jyamihud/VCStudio/raw/master/"+openlink)

                    # Sometimes we might get a 404 error page
                    
                    if not resp.data.decode("utf-8").startswith("<!DOCTYPE html>"):

                        s = open(openlink, "wb")
                        s.write(resp.data)
                        s.close()
                    else:
                        1/0 # Else we want to execute the exception
                except:

                    # We gonna make a simple 404 page
                    # And load it

                    openlink = "/tmp/404-error-"+str(version)+".md"
                    s = open(openlink, "w")
                    s.write("# Version "+str(version)+" No page :(\n\n")
                    s.write("You can try")
                    s.write("![](../../settings/themes/OldSchool/icons/lbry.png)")
                    s.write("[the LBRY link]("+link.replace("(","%28").replace(")","%29")+").\n\n")
                    s.write("![](../../settings/themes/OldSchool/icons/question.png) [What is LBRY?](../../wiki/extra/LBRY.md)")
                    s.close()
                    
                
            win.current["mdfs"]["update_markdown"] = openlink # Loading MD file into viever
            win.current["update_markdown_files"] = files      # Files, for list of updates 
        
        UI_elements.roundrect(layer, win, 
            current_X + 50 + win.scroll["pm_update"],
            20,
            300,
            40,
            10,
            button=do,
            tip=talk.text("update_read_version_notes"),
            fill=False,
            clip=clip)
        layer.stroke()

        # Loading markdown page at start of the update window
        if not win.current["mdfs"]["update_markdown"]:
            do()
        
        current_X = current_X + 310

    # And finally the scroller for the top bar.
    UI_elements.scroll_area(layer, win, "pm_update", 
        50,
        20,
        win.current["w"]-100,
        80,
        current_X,
        bar=True,
        mmb=True,
        sideways=True,
        url="update_layer"
        )

    
    return surface
