import Apikeys
import inspect
import os
import requests
from datetime import datetime

TEMPLATES_DIR = (
    "/Users/normrasmussen/Documents/Work/Custom_Templates/Template-backup-tmp/"
)
URL = "https://api.northpass.com/"


def test():
        print(name)


def template_endpoint():
    for customer, apikey in inspect.getmembers(Apikeys):
        global customer_path = os.path.join(TEMPLATES_DIR, customer)
        os.mkdir(customer_path)

        count = 0
        templates = []

        while True:
            count += 1
            endpoint = f"v2/custom_templates?page={count}"
            headers = {
                "accept": "application/json",
                "content-type": "application/json",
                "X-Api-Key": apikey,
            }
            response = requests.get(URL + endpoint, headers=headers)
            data = response.json()
            for response in data["data"]:
                last_updated = response["attributes"]["updated_at"].split("T")
                # full_updated = response["attributes"]["updated_at"]
                # full_updated = datetime.fromisoformat(full_updated)
                last_updated = last_updated[0]
                name, body, last_updated = (
                    response["attributes"]["name"],
                    response["attributes"]["body"],
                    last_updated,
                )
                templates.append((name, body, last_updated))

        if data["data"] == []:
            break

    save_templates(templates)


def save_templates(templates):
    for tupe in templates:
        file_name = tupe[0] + ".liquid"
        file_body = tupe[1]
        final_path = os.path.join(customer_path, file_name)

        with open(final_path, "w+") as temp:
            temp.write(file_body)
            temp.close


if __name__ == "__main__":
    template_endpoint()
