
__version__ = "2.00"

import sys

from format import array_to_string, format_objects_to_markdown, read_last_lines
from terminal import print_error, print_green, print_yellow

if sys.version_info[0] == 2:
    print("Python 3 is required.")
    sys.exit(1)

import os
import os.path
import subprocess
from pathlib import Path
import requests
from obsfuschatedList import obfuschatedList

def Fract_Sec(s):
    temp = float()
    temp = float(s) / (60*60*24)
    d = int(temp)
    temp = (temp - d) * 24
    h = int(temp)
    temp = (temp - h) * 60
    m = int(temp)
    temp = (temp - m) * 60
    sec = temp
    return d,h,m,sec
    #endef Fract_Sec

failedBuilds = []

def pack_directory(directory):
    output_dir = os.getenv("OUTPUT_DIR")

    if not output_dir:
        print_error("OUTPUT_DIR not set")
        sys.exit(1)

    absolute_output_dir = os.path.abspath(output_dir)
    if not os.path.exists(absolute_output_dir):
        os.makedirs(absolute_output_dir)

    try:
        absolute_path = os.path.abspath("P:/braf/" + directory)
        print("Packing Directory {}".format(absolute_path))
        print("Target Directory {}".format(absolute_output_dir))

        cmd = ["pboproject","-P", absolute_path, "+M={}".format(absolute_output_dir)]

        if directory in obfuschatedList:
            cmd.append("+O")
        else:
            cmd.append("-O")

        returnOutput = subprocess.call(cmd)

        print("Builded {}".format(directory))

        if returnOutput == 0:
            print_green("Addon {} successfully built/signed.".format(directory))
        else:
            print_error("Addon {} not successfully built/signed".format(directory))
            temp_dir = r'P:/temp'
            if os.path.exists(temp_dir):
                errorLog = read_last_lines(os.path.join(temp_dir,directory+".packing.log"), 10)
                if errorLog is not None:
                    print_yellow("The last 10 lines of the log are:\n {}".format(errorLog))
                else:
                    print_error("The log could not be found.")
                failedBuilds.append({"directory": directory, "errorLog": [errorLog]})
            else:
                print_error("The temp folder could not be found.")
                failedBuilds.append({"directory": directory, "errorLog": ["The log could not be found."]})
            print ("Resuming build...")

    except subprocess.CalledProcessError as e:
        print(f"Error running command in {directory}: {e}")

def main():
    if len(sys.argv) < 2:
        print_error("No directories provided!")
        sys.exit(1)

    if len(sys.argv) == 2 and " " in sys.argv[1]:
        directories = sys.argv[1].split()
    else:
        directories = sys.argv[1:]

    for directory in directories:
        path = Path(directory)
        if path.is_dir():
            pack_directory(directory)
        else:
            print_error(f"{directory} is not a valid directory path")
            sys.exit(1)

    print_yellow("There were {} failed builds".format(len(failedBuilds)))

    discord_webhook = os.getenv("DISCORD_WEBHOOK")

    if len(failedBuilds) > 0:
        print_error("There were {} failed builds:\n {}".format(len(failedBuilds), (failedBuilds)))

        if discord_webhook != "":
            requests.post(discord_webhook, json={
                "content": "**There were {} failed builds:**\n {}\n".format(len(failedBuilds), format_objects_to_markdown(failedBuilds)),
                "username": "Build Failed",
                "avatar_url": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQE6prA5NL5oqTqEDMAkU823YY4xGMq9c3ucg&s"
            })

        sys.exit(1)
    else:
        print_green("All builds were successful")

        if discord_webhook != "":
            if len(directories) > 0:
                requests.post(discord_webhook, json={
                    "content": "**All builds were successful** \n builded addons: {}".format(array_to_string(directories)),
                    "username": "Build Success",
                    "avatar_url": "https://cdn1.iconfinder.com/data/icons/basic-ui-elements-color-round/3/15-512.png"
                })

        sys.exit(0)

if __name__ == "__main__":
    main()