#################################################################################
#     This file is part of Mana Launcher.
#     Copyright (C) 2021  Jesusalva <jesusalva@tmw2.org>
#
#     Distributed under the MIT license.
#################################################################################

init -3 python:
    renpy.add_python_directory("python-extra")
    import requests, zlib, base64, sys, copy, uuid, time, json, traceback
    import os.path, os, shutil, subprocess, hashlib, zipfile
    # non-free imports
    import _renpysteam as steam
    import discord_rpc

    print("\n[STDBY] Loading Basic functions.......")

    # set PYTHON_VERSION variable (e.g. 2715, 3605 etc.)
    PYTHON_VERSION="%d%d%02d" % (sys.version_info.major, sys.version_info.minor, sys.version_info.micro)
    PYTHON_VERSION=int(PYTHON_VERSION)

    # Ren'Py should come with Python 2.7.10 (2710), but just in case
    # After all, I only tested with 2.7.10, 2.7.13 and 2.7.15
    if (PYTHON_VERSION < 2700 or PYTHON_VERSION > 3000):
        execute=subprocess.run
        # FIXME: check must be set and True
        raise Exception("WARNING: Python version is not 2.7\nStrange bugs may happen on your client.\n\nClick on \"Ignore\" to continue.\nClick on \"Quit\" to exit.")
    else:
        execute=subprocess.call

    #############################################################################
    ## Configuration and Defaults
    if (persistent.discord is None):
        persistent.discord = True
    if (persistent.client is None):
        persistent.client = "manaplus"
    if (persistent.iconify is None):
        persistent.iconify = True

    #############################################################################
    #, "themanaworld.org", "germantmw.de", "moubootaurlegends.org"]
    VAULT_HOST = "http://localhost:13370"
    #############################################################################

    # Encodes something to md5
    def md5(string):
        return hashlib.md5(string.encode()).hexdigest()

    def md5sum(f):
        md5=hashlib.md5()
        fp=open(f, "rb")
        ct=fp.read()
        md5.update(ct)
        rt=copy.copy(md5.hexdigest())
        fp.close()
        del ct
        return rt

    # Smart Print command
    def stdout(message, bd=False):
        if config.developer:
            if renpy.android:
                if not renpy.is_init_phase():
                    renpy.notify(message)
            else:
                if bd:
                    print("\033[1m%s\033[0m" % message)
                else:
                    print(message)
            renpy.write_log("[DEBUG] %s" % message)
        else:
            renpy.write_log("[GAME] %s" % message)
        return

    # Smart wait
    def sdelay(delta=0.02):
        try:
            renpy.pause(delta, hard=True)
        except:
            time.sleep(delta)
        return

    # IF Then Else (IFTE)
    def ifte(ifs, then, elses):
        if (ifs):
            return then
        else:
            return elses

    # Returns number of seconds since UNIX EPOCH
    def now():
        return int(time.time())

    # File Managment Functions
    def get_path(path):
        if True or renpy.android:
            path=path.replace("/", "_")
            #return renpy.loader.get_path(path)
            return renpy.config.savedir + "/" + path
        else:
            return renpy.loader.get_path(path)

    # Global classes
    # We need to override standard list method. Original by Triptych (stackoverflow)
    class dlist(list):

        def __setitem__(self, index, value):
            size = len(self)
            if index >= size:
                self.extend(None for _ in range(size, index + 1))

            list.__setitem__(self, index, value)

    # Search for array[?][key]==search in an array of dicts
    # Returns the dictionary, or returns ERR_INVALID
    def dl_search(array, key, search):
        try:
            r=(item for item in array if item[key] == search).next()
        except:
            r=ERR_INVALID
        if r is None:
            r=ERR_INVALID
            stdout("dlsearch: r is None")
        return r

######### Done with pre-init
label splashscreen:
    show TMW2 at truecenter with fade
    python:
        if persistent.hello is None:
            p1=2.5
            p2=1.5
            persistent.hello=True
        else:
            p1=0.5
            p2=0.5
    pause p1
    hide TMW2 with Dissolve(p2)
    call before_main_menu
    return

label die:
    $ stdout("Program died.")
    pause
    return

####### Defaults
default statusmsg = "Not yet initialized"
default progress = 0
default responsive = True
default has_steam = False
default SCR_PROMPT = None
default SCR_RESULT = None