const axios = require("axios")
const fs = require("fs");
const { parse } = require("csv-parse");
// let xApiKey = 'XxDBlgH3CNSiD6yDgqZgpjjxB'    //Austin SCHOOL API KEY
let xApiKey = 'HdZFoXGCFpt8NnTOzIQY0kVDj' // <<< This is for sandata's school

let allNPUsers = [];
let allUsers = [];

let getAllNPUsers = async (num) => {
    let page = num;
    console.log(`RETRIEVING PAGE ${num} OF USERS`)

    await axios({
        method: 'get',
        // url: 'https://api.northpass.com/v2/people/?page=' + page + '&limit=100',
        url: 'https://api.northpass.com/v2/people/?page=' + page + '&limit=100',
        headers: {
            'accept': '*/*',
            'x-api-key': xApiKey,
            'content-type': 'application/json'
        }
    })
    .then(async (res) => {

    if (res.data.links.next != null) {
        page++;
        for (let i = 0; i < res.data.data.length; i++) {
            allNPUsers.push(res.data.data[i]);
        }
        await getAllNPUsers(page);
    } else {
        for (let i = 0; i < res.data.data.length; i++) {
            allNPUsers.push(res.data.data[i]);
        }
    }
    })
    .catch(err => {
        console.log(err);
    })
}

// let getAllNPGroups = async (num) => {
//     let page = num;
//     console.log(`RETRIEVING PAGE ${num} OF GROUPS`)

//     await axios({
//         method: 'get',
//         // url: 'https://api.northpass.com/v2/groups/?page=' + page + '&limit=100',
//         url: 'https://api.northpass.com/v2/groups/?page=' + page + '&limit=100',
//         headers: {
//             'accept': '*/*',
//             'x-api-key': xApiKey,
//             'content-type': 'application/json'
//         }
//     })
//     .then(async (res) => {
//     // console.log(res.data.data)

//     // console.log(res.data.links.next != null);
//     if (res.data.links.next != null) {
//         // console.log("not on last page")
//         page++;
//         for (let i = 0; i < res.data.data.length; i++) {
//             //console.log(res.data.data[i].attributes.name)
//             allNPGroups[res.data.data[i].attributes.name] = res.data.data[i].id
//         }
//         await getAllNPGroups(page);
//     } else {
//         //console.log("on last page")
//         for (let i = 0; i < res.data.data.length; i++) {
//             //console.log(res.data.data[i].attributes.name)
//             // allNPGroups[res.data.data[i].id] = res.data.data[i].attributes.name
//             allNPGroups[res.data.data[i].attributes.name] = res.data.data[i].id
//         }
//     }
//     })
//     .catch(err => {
//         console.log(err);
//     })
// };

// -----------------------------------------------------------------------------------------------------------------------------------------------------------
// CLEAR FUNCTIONS

const clearSchoolUsers = async (someArray, start) => {
    let iterator = start;
    let user = someArray[iterator];

    // console.log(user.attributes.email)

    if(allUsers.indexOf(user.attributes.email.toLowerCase()) > -1){
        // console.log('SHOULD BE CLEARED >>> ' + user.attributes.email)
        // console.log(user);
        await axios({
            method: "delete",
            // url: `https://api.northpass.com/v2/people/${user.id}`,
            url: `https://api.northpass.com/v2/people/${user.id}`,    
            headers: {
                accept: "*/*",
                "x-api-key": xApiKey,
                "content-type": "application/json",
            },
        })
        .then(async () => {
            console.log(`TERMINATED USER WITH EMAIL: ${user.attributes.email}`)
            console.log('\x1b[36m%s\x1b[0m', `COMPLETED DELETING USER AT INDEX ${iterator}`);
            iterator += 1;

            if(iterator >= someArray.length){
                return;
            } else {
                await clearSchoolUsers(someArray, iterator)
            }
        })
    } else {
        iterator += 1;

        if(iterator >= someArray.length){
            return;
        } else {
          await clearSchoolUsers(someArray, iterator)
        }
    }
}

// const clearSchoolGroups = async (someArray, start) => {
//     // console.log(someArray)
//     let iterator = start;
//     let groupName = someArray[iterator];

//     let groupIDVal = allNPGroups[groupName];
//     if(groupName != 'PRIMARY ACCOUNT'){
//         await axios({
//             method: "delete",
//             // url: `https://api.northpass.com/v2/groups/${groupIDVal}`,
//             url: `https://api.northpass.com/v2/groups/${groupIDVal}`,
//             headers: {
//                 accept: "*/*",
//                 "x-api-key": xApiKey,
//                 "content-type": "application/json",
//             },
//         })
//         .then(async () => {
//             console.log(`TERMINATED GROUP WITH UUID: ${groupIDVal}`)
//             console.log('\x1b[36m%s\x1b[0m', `COMPLETED DELETING GROUP AT INDEX ${iterator}`);
//             iterator += 1;

//             if(iterator >= someArray.length){
//                 return;
//             } else {
//                 await clearSchoolGroups(someArray, iterator)
//             }
//         })
//     } else {
//         iterator += 1;

//         if(iterator >= someArray.length){
//             return;
//         } else {
//             await clearSchoolGroups(someArray, iterator)
//         }
//     }
// }

let removeUsers = async () => {
    await getAllNPUsers(1)
    .then(async () => {
        await clearSchoolUsers(allNPUsers, 0);
    })
}

// let removeGroups = async () => {
//     await getAllNPGroups(1)
//     .then(async () => {
//         // console.log(Object.keys(allNPGroups))
//         await clearSchoolGroups(Object.keys(allNPGroups), 0);
//     })
// }

fs.createReadStream("./sandataPAusers.csv")
.pipe(parse({ delimiter: ','}))
.on("data", function (row) {

    if(row[0] !== 'Email'){
      // allUsers.push({
      //   email: row[0]
      // });
      allUsers.push(row[0].toLowerCase());
    }
})
.on("error", function (error) {
    console.log(error.message);
})
.on("end", async function () {
    console.log("FINISHED COLLECTING ALL NEW USERS");
    console.log(allUsers);
    console.log(allUsers.length);

    // await executeFunctionChain();
    await removeUsers();
})
// removeGroups();