"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
const https = require("https");
const querystring = __importStar(require("querystring"));
var queryParameters = {
    cards: "all",
    card_fields: "id,closed,idBoard,idList,name,shortLink",
    card_attachments: "false",
    labels: "all",
    label_fields: "all",
    labels_limit: "1000",
    lists: "all",
    list_fields: "all",
    members: "all",
    organization: "true",
    organization_fields: "id,displayName,idMemberCreator",
    fields: "id,name,closed,idOrganization,pinned,starred,url,shortLink,idMemberCreator",
};
class default_1 {
    constructor(db, appKey, token) {
        this.db = db;
        this.appKey = appKey;
        this.token = token;
    }
    async run() {
        return this.process(await this.getBoards());
    }
    async process(data) {
        let board;
        for (board of data) {
            try {
                await this.processBoard(board);
                await this.processLists(board.lists);
                await this.processCards(board.cards);
                await this.processMembers(board.members);
                if (board.organization) {
                    await this.processOrg(board.organization);
                }
            }
            catch (e) {
                console.error("Error processing board", board);
                throw e;
            }
        }
    }
    async processOrg(org) {
        // Insert into boards
        return this.db.upsert("orgs", {
            id: org.id,
            displayName: org.displayName,
            creatorId: org.idMemberCreator,
        });
    }
    async processBoard(board) {
        // Insert into boards
        await this.db.upsert("boards", {
            id: board.id,
            name: board.name,
            orgId: board.idOrganization,
            creatorId: board.idMemberCreator,
            shortLink: board.shortLink,
            closed: board.closed ? 1 : 0,
        });
        return this.processLabels(board.labels);
    }
    async processLabels(labels) {
        for (let label of labels) {
            await this.db.upsert("labels", {
                id: label.id,
                name: label.name,
                boardId: label.idBoard,
                color: label.color,
            });
        }
    }
    async processLists(lists) {
        for (let list of lists) {
            await this.db.upsert("lists", {
                id: list.id,
                name: list.name,
                boardId: list.idBoard,
                closed: list.closed ? 1 : 0,
            });
        }
    }
    async processCards(cards) {
        for (let card of cards) {
            await this.db.upsert("cards", {
                id: card.id,
                name: card.name,
                boardId: card.idBoard,
                listId: card.idList,
                shortLink: card.shortLink,
            });
        }
    }
    async processMembers(members) {
        for (let member of members) {
            await this.db.upsert("members", {
                id: member.id,
                username: member.username,
                fullName: member.fullName,
                initials: member.initials,
            });
        }
    }
    async getBoards() {
        let boards = await this.api("/members/me/boards");
        // Fetch each board with all details
        return await Promise.all(boards.map(async (b) => {
            return await this.api("/boards/" + b.id, queryParameters);
        }));
    }
    async api(url, options) {
        return this.get(`https://api.trello.com/1${url}`, options);
    }
    async get(url, options) {
        options = options || {};
        const key = this.appKey;
        const token = this.token;
        return new Promise(function (resolve, reject) {
            const https = require("https");
            url =
                url +
                    "?" +
                    querystring.stringify(Object.assign({ key,
                        token }, options));
            https
                .get(url, (resp) => {
                let data = "";
                // A chunk of data has been received.
                resp.on("data", (chunk) => {
                    data += chunk;
                });
                // The whole response has been received. Print out the result.
                resp.on("end", () => {
                    try {
                        resolve(JSON.parse(data));
                    }
                    catch (e) {
                        return reject(e);
                    }
                });
            })
                .on("error", (err) => {
                return reject(err);
            });
        });
    }
}
exports.default = default_1;
//# sourceMappingURL=sync.js.map