import Apikeys
import json
import requests
import pandas as pd
import pprint

pp = pprint.PrettyPrinter(indent=4)
df = pd.DataFrame()
BASEURL = "https://api.northpass.com/v2"
LEARNFILTER = "?filter[partnerships_type][eq]=Partnerships::Learner"
APIKEY = Apikeys.SANDATA
HEADERS = {"accept": "application/json", "content-type": "application/json", "X-Api-Key": APIKEY}
PERSON_GROUPS = []
PPL_DELETIONS = []
GROUPS_LIST = []
ADMINS_NOT_TO_DELETE = [
    "269b4e46-74fa-49f9-b1a3-59a15180b377",
    "23eb155c-395f-40a5-adb8-ef348bc85051",
    "cebe6de7-af0d-46cb-bf0a-a461fb0bed63",
    "e134030d-a2a9-4de2-b4d5-87081feee18a",
    "65b6924b-e0b3-4e8d-a9ff-140fb9de9453",
    "1cc4762e-3a6d-48b5-a8bf-bbe98e00c72e",
    "5c457837-5ad5-486e-86b7-ea65353565b0",
    "5e89fba5-3d12-4961-af46-2f4f131e7387",
    "b0098337-7b7e-45e5-b645-e71c40387cbb",
    "c111dc44-470e-4c74-a7ce-688dff5e3476",
    "a6c6469b-8978-4899-a9c8-bbc5cdb29e5e",
]


def get_groups():
    count = 1
    while True:
        url = f"{BASEURL}/groups?limit=100&page={count}"
        resp = requests.get(url, headers=HEADERS)
        json = resp.json()
        nextlink = json["links"]
        count += 1

        for data in json["data"]:
            group_name = data["attributes"]["name"]
            members = data["attributes"]["memberships_count"]
            id = data["id"]
            if "ST - OH" in group_name or "ST - CA" in group_name:
                pass
            else:
                if members > 0:
                    grouple = (id, group_name, members)
                    GROUPS_LIST.append(grouple)

        if "next" not in nextlink:
            break

    get_ppl_from_groups(GROUPS_LIST)


def get_ppl_from_groups(GROUPS_LIST):
    for single_group in GROUPS_LIST:
        print(single_group)
        group_count = 1
        while True:
            group_url = f"{BASEURL}/groups/{single_group[0]}/memberships?limit=100&page={group_count}"
            group_resp = requests.get(group_url, headers=HEADERS)
            groupson = group_resp.json()
            group_count += 1
            nextlink = groupson["links"]

            for data in groupson["data"]:
                id = data["relationships"]["person"]["data"]["id"]
                if id in ADMINS_NOT_TO_DELETE:
                    pass
                else:
                    PPL_DELETIONS.append(id)

            if "next" not in nextlink:
                break

        print("Deleting People.... Hold on to your butts.")
        if len(PPL_DELETIONS) > 1500:
            for chunk in range(0, len(PPL_DELETIONS), 1500):
                i = chunk
                delete_url = f"{BASEURL}/bulk/people/delete"
                chunk_to_del = PPL_DELETIONS[i:i+1500]
                payload = { "payload": chunk_to_del }
                print(payload)
                try:
                    del_resp = requests.post(delete_url, json=payload, headers=HEADERS)
                    print(del_resp)
                    if del_resp.status_code == 400:
                        print(
                            f"Issue with Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                        )
                        print("Writing person IDs to file...")
                        with open("./Sandata_errors.txt", "a") as file:
                            file.write(f"{single_group}... \n {payload}")
                            file.close()
                    if del_resp.status_code == 401:
                        print(
                            f"Issue with Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                        )
                        print("Writing person IDs to file...")
                        with open("./Sandata_errors.txt", "a") as file:
                            file.write(f"{single_group}... \n {payload} \n")
                            file.close()
                    if del_resp.status_code == 422:
                        print(
                            f"Issue with body for Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                        )
                        print("Writing person IDs to file...")
                        with open("./Sandata_errors.txt", "a") as file:
                            file.write(f"{single_group}... \n {payload} \n")
                            file.close()
                    status = str(del_resp.status_code)
                    if "20" in status:
                        print(f"Some success! Status code: {del_resp.status_code}")
                except requests.exceptions.HTTPError as h:
                    print(f"Exception HTTPError: {h} \n Passing onto next loop.")
                    pass
                finally:
                    print(f"{single_group[1]} has been completed. Moving onto next group.")
        else:
            delete_url = f"{BASEURL}/bulk/people/delete"
            payload = { "payload": PPL_DELETIONS }
            try:
                del_resp = requests.post(delete_url, json=payload, headers=HEADERS)
                print(del_resp)
                if del_resp.status_code == 400:
                    print(
                        f"Issue with Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                    )
                    print("Writing person IDs to file...")
                    with open("./Sandata_errors.txt", "a") as file:
                        file.write(f"{single_group}... \n {payload}")
                        file.close()
                if del_resp.status_code == 401:
                    print(
                        f"Issue with Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                    )
                    print("Writing person IDs to file...")
                    with open("./Sandata_errors.txt", "a") as file:
                        file.write(f"{single_group}... \n {payload} \n")
                        file.close()
                if del_resp.status_code == 422:
                    print(
                        f"Issue with body for Group: {single_group[1]}... {del_resp.status_code} - {del_resp.text}"
                    )
                    print("Writing person IDs to file...")
                    with open("./Sandata_errors.txt", "a") as file:
                        file.write(f"{single_group}... \n {payload} \n")
                        file.close()
                status = str(del_resp.status_code)
                if "20" in status:
                    print(f"Some success! Status code: {del_resp.status_code}")
            except requests.exceptions.HTTPError as h:
                print(f"Exception HTTPError: {h} \n Passing onto next loop.")
                pass
            finally:
                print(f"{single_group[1]} has been completed. Moving onto next group.")



def get_people():
    """
    This is no longer being used.
    """
    count = 0
    while True:
        url = f"{BASEURL}/people{LEARNFILTER}&limit=100&page={count}"
        resp = requests.get(url, headers=HEADERS)
        json = resp.json()
        nextlink = json["links"]

        print(count)
        count += 1
        for data in json["data"]:
            id = data["id"]
            PERSON_GROUPS.append(id)
            email = data["attributes"]["email"]
            groups = data["relationships"]["groups"]

            for key, val in groups.items():
                if groups != "":
                    for group in val:
                        uuid = group["id"]
                        group_url = f"https://api.northpass.com/v2/groups/{uuid}"
                        response = requests.get(group_url, headers=HEADERS)
                        try:
                            group_resp = response.json()

                            group_name = group_resp["data"]["attributes"]["name"]
                            # print(email, group_name)
                            if "ST - OH" in group_name or "ST - CA" in group_name:
                                pass
                            else:
                                PPL_DELETIONS.append(id)
                                print(email, group_name)

                            PERSON_GROUPS.append((id, email, group_name))
                        except JSONDecodeError as e:
                            print(f"There was a JSON Error --> {e}")
                            dataerror = df.from_records(PERSON_GROUPS)
                            dataerror.to_csv("~/Downloads/Sandata-err-all-ppl")
                            print(dataerror)
                            print(len(PERSON_GROUPS))

                            datadelerr = df.from_records(PPL_DELETIONS)
                            datadelerr.to_csv("~/Downloads/Sandata-err-ppl-to-delete")
                            pass
                        finally:
                            pass

                else:
                    PERSON_GROUPS.append((id, email, "No Group"))

        if "next" not in nextlink:
            break

    dataframe = df.from_records(PERSON_GROUPS)
    dataframe.to_csv("~/Downloads/Sandata-all-ppl")
    print(dataframe)
    print(len(PERSON_GROUPS))

    datadel = df.from_records(PPL_DELETIONS)
    datadel.to_csv("~/Downloads/Sandata-ppl-to-delete")


# def parse_groups(id, grouplist):
#     for uuid in grouplist:
#     url = "https://api.northpass.com/v2/groups/{uuid}"
"""
Bulk delete endpoint: https://api.northpass.com/v2/bulk/people/delete
Payload:
payload = { "payload": ["asd", "asd", "asd"] }
        """

if __name__ == "__main__":
    get_groups()
