import os
import json
from pathlib import Path

from speedbuild.auth.serverCall import manageServerCall


home = str(Path.home())
template_home = os.path.join(home,".sb_zip")

def updatePushHistory(data,template_path):
    config_path = os.path.join(template_path,"history.json")
    with open(config_path,"w") as file:
        json.dump(data,file,indent=4)

def getPushHistory(template_path):
    config_path = os.path.join(template_path,"history.json")
    if not os.path.exists(config_path):
        return None
    
    with open(config_path,"r") as file:
        return json.loads(file.read())

def pushTemplate(name,framework):
    template_path = os.path.join(template_home,name)
    if not os.path.exists(template_path):
        print("Could not find template with name ",name)
        return
    
    push_history = getPushHistory(template_path)
    push_action = "update"
    
    if push_history == None:
        repo = int(input("What repo are you pushin to (enter repo id) : "))
        description = input("Enter template short description : ")
        push_history = {
            "name":name,
            "description":description,
            "framework": framework,
            "versions":[],
            "repo":repo
        }

        push_action = "create"
    else:
        repo = push_history['repo']

    filesInTemplatePath = [i for i in os.listdir(template_path) if (i.endswith(".zip") and i not in push_history['versions']) and not i.endswith("lts.zip")]

    if len(filesInTemplatePath) > 0 and "lts.zip" not in filesInTemplatePath:
        filesInTemplatePath.append("lts.zip")
    elif push_action == "create" and "lts.zip" not in filesInTemplatePath:
        filesInTemplatePath.append("lts.zip")

    filesInTemplatePath = sorted(filesInTemplatePath, key=lambda x: float(x.replace('.zip','')) if x[0].isdigit() else float('inf'))

    for zipFile in filesInTemplatePath:
        print("pushing ",zipFile)
        # send to server here
        fileFullPath = os.path.join(template_path,zipFile)

        formData = {
            "name":push_history['name'],
            "repo":push_history['repo'],
            "description":push_history['description'],
            "framework":framework,
            "version": os.path.basename(zipFile).replace(".zip","").lstrip("/"),
            "action":push_action
        }

        files = {
            "template": open(fileFullPath, "rb")
        }
        try:
            print("pushing to server")
            manageServerCall("POST","api/template/",formData,files,True)
            push_history['versions'].append(zipFile)
            suceeded = True
            if push_action == "create":
                push_action = "update"
        except ValueError as error:
            print(error)
            suceeded = False
            break
        # "name": 2,

    if suceeded:
        updatePushHistory(push_history,template_path)

# pushTemplate("test_hello","express",1)
