import { Logger } from '../logging/logger.js';
import StringFormatter from '../utils/stringFormatter.js';
import {BasePoller} from "../base/basePoller.js";
import {Requester} from "../utils/requester.js";

export class InstagramPoller extends BasePoller {

    /**
     *
     * @param rawPostListUrl {string}
     * @param rawMediaDetailsUrl {string}
     * @param tokenManager {InstagramTokenManager}
     */
    constructor(rawPostListUrl, rawMediaDetailsUrl, tokenManager){
        super();
        this.rawPostListUrl = rawPostListUrl;
        this.rawMediaDetailsUrl = rawMediaDetailsUrl;
        this.tokenManager = tokenManager;
    }

    async pollOnce(){
        try{
            let userData = this.tokenManager .getUserData(0);
            let postListUrl = this.formatPostListUrl(userData.userId, userData.token);

            let mediaData = await Requester.doGetRequest(postListUrl);
            console.log(mediaData);
            let mediaId = this.getMediaId(mediaData);
            let detailsUrl = this.formatMediaDetailsUrl(mediaId, userData.token);

            let mediaDetails = await Requester.doGetRequest(detailsUrl);
            console.log(mediaDetails);
            console.log({permalink : mediaDetails.permalink, userId : userData.userId});

            super.emit("newPost", {permalink : mediaDetails.permalink, userId : userData.userId});
        } catch(err) {
            console.error(err);
            await Logger.error(`Unbale to fetch instagram content for`, err)
        }
    }

    formatPostListUrl(userId, accessToken){
        return StringFormatter.format(this.rawPostListUrl, [{key: "userId", value: userId}, {key: "access_token", value: accessToken}]);
    }

    formatMediaDetailsUrl(mediaId, accessToken){
        return StringFormatter.format(this.rawMediaDetailsUrl, [{key: "access_token", value: accessToken}, {key: "media_id", value: mediaId}]);
    }

    getMediaId(mediaData){
        return mediaData.data[0].id;
    }
}