import { Injectable, HttpException, HttpStatus, OnModuleInit } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import axios from 'axios';
const moment = require('moment');
import { env } from 'process';
import { Constants } from 'src/common/constants';
import { FacebookPages } from 'src/entities/facebook-pages.entity';
import { FacebookPosts } from 'src/entities/faceboook-posts.entity';
import { InstagramProfiles } from 'src/entities/instagram-profile.entity';
import { KeyType, Settings } from 'src/entities/settings.entity';
import { SocialMediaPosts, SocialType } from 'src/entities/social-media-posts.entity';
import { SocialMedias } from 'src/entities/social-medias.entity';
import { Users } from 'src/entities/users.entity';
import { responseMessages } from 'src/messages/response-messages';
import { In, IsNull, Not, Repository } from 'typeorm';
import { EncryptionService } from '../encryption/encryption.service';
import { constants } from 'buffer';
import { uploadFileToS3 } from 'src/common/config/upload-s3-file-using-link';

@Injectable()
export class FacebookServices implements OnModuleInit {
    public s3Config = {};
    constructor(
        private encryptionService: EncryptionService,
        @InjectRepository(Users)
        private Users: Repository<Users>,

        @InjectRepository(SocialMedias)
        private SocialMedias: Repository<SocialMedias>,

        @InjectRepository(FacebookPages)
        private FacebookPages: Repository<FacebookPages>,

        @InjectRepository(FacebookPosts)
        private FacebookPosts: Repository<FacebookPosts>,

        @InjectRepository(Settings)
        private Settings: Repository<Settings>,

        @InjectRepository(InstagramProfiles)
        private InstagramProfiles: Repository<InstagramProfiles>,


        @InjectRepository(SocialMediaPosts)
        private SocialMediaPosts: Repository<SocialMediaPosts>,

    ) { }

    async onModuleInit() {

        this.s3Config = {
            accessKeyId: await this.encryptionService.decrypt(process.env.AWS_ACCESS_KEY_ID),
            secretAccessKey: await this.encryptionService.decrypt(process.env.AWS_SECRET_ACCESS_KEY),
            region: process.env.AWS_DEFAULT_REGION,
        }
    }

    /**
     * Get the list of all pages of a facebook user.
     * Save the pages in the database.
     * Get the details of each page.
     * @param request The request object.
     * @param authUser The authenticated user.
     * @returns A boolean indicating whether the operation was successful.
     * @throws A HttpException if an error occurs.
     */
    async facebook(request: any, authUser: any) {
        try {
            const pageUrl = `${process.env.FACEBOOK_BASE_URL}me`;
            const headers = {
                Authorization: `Bearer ${request.access_token}`,
            };
            const params = {
                fields: 'id,name,first_name,last_name,email,picture,accounts{fan_count,features,followers_count,general_info,link,location,name,phone,access_token,bio,description,likes}',
            };
            // GET THE PAGE LIST
            const pageResponse = await this.getAxios(pageUrl, headers, params);

            if (pageResponse) {
                console.log(pageResponse.accounts.data.length)
                if (pageResponse.accounts.data.length) {
                    const socialMedia = await this.saveSocialMedia(request, authUser);
                    if (socialMedia) {
                        await this.getFacebookPageDetails(pageResponse.accounts, socialMedia, authUser);
                    }
                }
                else {
                    throw new HttpException(responseMessages.en.user.social_media.facebook_page_not_exists, HttpStatus.BAD_REQUEST);
                }
                if (!authUser.is_profile_pic_updated) {
                    let image = pageResponse.picture.data.url;
                    const s3Response = await uploadFileToS3(image, `images/profile/`, this.s3Config);
                    if (s3Response) {
                        authUser['image'] = s3Response.path
                    } else {
                        authUser['image'] = image;
                    }
                    // authUser['profile_picture_url'] = pageResponse.picture.data.url;
                }
                authUser['about_me'] = authUser['about_me'] !== null ? authUser['about_me'] : pageResponse.description;
                this.Users.save(authUser);
            }
            return true;
        } catch (error) {
            console.log(error.message)
            throw new HttpException(error.message, error.status);
        }
    }


    async instagramFacebook(request: any, authUser: any) {
        try {
            const socialMedia = await this.SocialMedias.findOne({ where: { id: request.instagram_social_media_id } });

            const pageUrl = `${process.env.FACEBOOK_BASE_URL}me`;
            const headers = {
                Authorization: `Bearer ${request.access_token}`,
            };
            const params = {
                fields: 'id,accounts{id,name,picture,access_token}',
            };
            // GET THE PAGE LIST
            const pageResponse = await this.getAxios(pageUrl, headers, params);

            if (pageResponse) {
                console.log(JSON.stringify(pageResponse.accounts.data))
                if (pageResponse.accounts?.data?.length) {
                    for (const page of pageResponse.accounts.data) {
                        const pageUrl = process.env.FACEBOOK_BASE_URL + page.id;
                        const headers = {
                            Authorization: `Bearer ${page.access_token}`,
                        };
                        const params = {
                            fields: 'id,name,picture,access_token,instagram_accounts{id,username}',
                        };
                        // GET THE PAGE LIST
                        const pageDetailResponse = await this.getAxios(pageUrl, headers, params);
                        console.log(JSON.stringify(pageDetailResponse.instagram_accounts))
                        if (pageDetailResponse) {
                            if (pageDetailResponse.instagram_accounts?.data?.length) {
                                for (const instagramInfo of pageDetailResponse.instagram_accounts.data) {

                                    if (socialMedia.social_user_name == instagramInfo.username) {
                                        const pageToken = await this.refreshToken(page.access_token);
                                        socialMedia.page_access_token = pageToken.access_token;
                                        socialMedia.page_access_token_expire_at = moment().add(58, 'days').format('YYYY-MM-DD');
                                        let instagramProfiles = await this.InstagramProfiles.findOne({ where: { socialMedia: { id: socialMedia.id } } });
                                        if (instagramProfiles) {
                                            instagramProfiles.facebook_page_id = page.id;
                                            instagramProfiles.facebook_page_name = page.name;
                                            instagramProfiles.facebook_page_picture_url = page.picture?.data?.url;
                                            await this.InstagramProfiles.save(instagramProfiles);
                                            this.SocialMedias.save(socialMedia);
                                        }
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            throw new HttpException("Your Instagram account is not linked to a Facebook Page. Please link your Instagram account to a Facebook Page and try again.", 404);
        } catch (error) {
            console.log(error.message)
            throw new HttpException(error.message, error.status);
        }
    }


    /**
     * Get the details of each page of a facebook user.
     * Save the pages in the database.
     * Check if the user is eligible for the platform.
     * If eligible, get the posts of the pages.
     * @param pages The list of pages of the facebook user.
     * @param socialMedia The social media entity of the user.
     * @param authUser The authenticated user.
     * @returns A boolean indicating whether the operation was successful.
     * @throws A HttpException if an error occurs.
     */
    async getFacebookPageDetails(pages, socialMedia, authUser) {
        try {
            const setting = await this.Settings.findOne({ where: { type: KeyType.FACEBOOK_FOLLOWERS_COUNT } });
            let isEligible = 0;
            let total_followers = 0;
            let total_following = 0;
            let post_count = 0;
            let facebookPages = [];
            for (const page of pages['data']) {
                const pageUrl = process.env.FACEBOOK_BASE_URL + page.id;

                const headers = {
                    Authorization: `Bearer ${page.access_token}`,
                };
                const params = {
                    fields: 'id,name,fan_count,followers_count,category,description,website,phone,location,emails,cover,picture,username,link,access_token',
                };

                if (page.followers_count >= parseInt(setting.value)) {
                    isEligible = 1;
                    // GET THE PAGE LIST
                    const pageDetailResponse = await this.getAxios(pageUrl, headers, params);
                    if (pageDetailResponse) {
                        if (!authUser.is_profile_pic_updated || authUser.image == null) {
                            await this.Users.update({ id: authUser.id }, { image: pageDetailResponse.picture?.data?.url, about_me: pageDetailResponse.description });
                        }
                        if (pageDetailResponse.username) {
                            const facebookPage = {
                                users: authUser, // Assuming nullable users
                                socialMedia: socialMedia, // Assuming no social media link initially
                                user_name: pageDetailResponse.username, // Maps the username field
                                description: pageDetailResponse.description || "", // Maps the description field
                                name: pageDetailResponse.name || "", // Maps the page name
                                emails: pageDetailResponse.emails ? pageDetailResponse.emails.join(', ') : "", // Join emails into a single string
                                page_logo: pageDetailResponse.picture?.data?.url || "", // Get page logo URL
                                cover_image: pageDetailResponse.cover?.source || "", // Get cover image URL
                                phone: pageDetailResponse.phone || "", // Maps the phone number
                                website: pageDetailResponse.website || "", // Maps the website URL
                                category: pageDetailResponse.category || "", // Maps the category field
                                facebook_page_id: pageDetailResponse.id || "", // Maps the Facebook page ID
                                fan_count: pageDetailResponse.fan_count || 0, // Maps the fan count
                                followers_count: pageDetailResponse.followers_count || 0, // Maps the followers count
                                city: pageDetailResponse.location?.city || "", // Maps the city
                                country: pageDetailResponse.location?.country || "", // Maps the country
                                latitude: pageDetailResponse.location?.latitude?.toString() || "", // Converts latitude to string
                                longitude: pageDetailResponse.location?.longitude?.toString() || "", // Converts longitude to string
                                street: pageDetailResponse.location?.street || "", // Maps the street address
                                zip: pageDetailResponse.location?.zip || "", // Maps the zip code
                                access_token: pageDetailResponse.access_token || "",
                                url: 'https://www.facebook.com/' + pageDetailResponse.username || "",
                            }
                            total_followers += page.followers_count;
                            console.log("name", pageDetailResponse.name)
                            console.log("username", pageDetailResponse.username)

                            facebookPages.push(pageDetailResponse.username);
                            const savePage = await this.FacebookPages.save(facebookPage)
                            await this.getFacebookPagePost(savePage, socialMedia, authUser)
                        }
                    }
                }
            }
            if (!isEligible) {
                this.unlinkFacebook(socialMedia)
                throw new HttpException(responseMessages.en.user.social_media.not_eligible, HttpStatus.PARTIAL_CONTENT);
            }
            //authUser['total_followers'] = Number(authUser['total_followers']) + Number(total_followers);
            if (!authUser['platforms']) {
                authUser['platforms'] = [];
            }
            if (!authUser['platforms'].includes('facebook')) {
                authUser['platforms'].push('facebook');
            }
            await this.Users.save(authUser);

            socialMedia = await this.SocialMedias.findOne({ where: { id: socialMedia.id } });
            socialMedia['follower_count'] = Number(total_followers);
            socialMedia['multiple_names'] = facebookPages;
            socialMedia['social_user_name'] = facebookPages[0];
            socialMedia['source_posts_from'] = 'facebook';
            await this.SocialMedias.save(socialMedia);
            // CREATE LONG TERM ACCESS TOKEN
            this.socialMediaRefreshToken(socialMedia)
            return true;
        } catch (error) {
            throw new HttpException(error.message, error.status);
        }
    }

    async getLivePost(page_id, nextPageToken = null) {
        const page = await this.FacebookPages.findOne({ where: { id: page_id } });
        if (page) {
            const pageUrl = process.env.FACEBOOK_BASE_URL + page.facebook_page_id + '/posts';

            const headers = {
                Authorization: `Bearer ${page.access_token}`,
            };
            const params = {
                fields: 'full_picture,message,message_tags,place,privacy,id,created_time,reactions.summary(total_count),comments.summary(total_count)',
                limit: Constants.POST_LIMIT, // Use the constant defined in the constants file
                after: nextPageToken
            };
            // GET THE PAGE LIST
            return await this.getAxios(pageUrl, headers, params);
        }
        return false;
    }

    async getSinglePost(page_id, post_id) {
        const page = await this.FacebookPages.findOne({ where: { facebook_page_id: page_id } });
        if (page) {
            const pageUrl = process.env.FACEBOOK_BASE_URL + post_id;

            const headers = {
                Authorization: `Bearer ${page.access_token}`,
            };
            const params = {
                fields: 'full_picture,message,message_tags,place,privacy,id,created_time,reactions.summary(total_count),comments.summary(total_count)',
                limit: 1
            };
            // GET THE PAGE LIST
            const response = await this.getAxios(pageUrl, headers, params);
            if (response) {
                return response;
            }
            return false;
        }
    }

    async getFacebookPostLink(link, user) {
        try {
            const [, , , pageId, , postId] = link.split('/');
            const page = await this.FacebookPages.findOne({ where: { facebook_page_id: pageId, users: { id: user.id } } });
            if (page) {
                const pageUrl = process.env.FACEBOOK_BASE_URL + pageId + `_` + postId;
                const headers = {
                    Authorization: `Bearer ${page.access_token}`,
                };
                const params = {
                    fields: 'full_picture,message,message_tags,place,privacy,id,created_time,reactions.summary(total_count),comments.summary(total_count)',
                    limit: Constants.POST_LIMIT
                };
                // GET THE PAGE LIST
                return await this.getAxios(pageUrl, headers, params);
            }
            return false;
        } catch (error) {
            console.log(error);
            return false;
        }
    }

    /**
     * Retrieves the posts from the Facebook page and saves the posts to the database.  
     * @param savePage - The Facebook page entity
     * @param socialMedia - The social media entity
     * @param authUser - The current user entity
     */
    async getFacebookPagePost(savePage, socialMedia, authUser) {
        const pageUrl = process.env.FACEBOOK_BASE_URL + savePage.facebook_page_id + '/posts';
        await this.FacebookPosts.delete({ id: savePage.id });
        await this.SocialMediaPosts.delete({ socialMedia: { id: socialMedia.id } });
        const headers = {
            Authorization: `Bearer ${savePage.access_token}`,
        };
        const params = {
            fields: 'full_picture,message,message_tags,place,privacy,id,created_time,reactions.summary(total_count),comments.summary(total_count)',
            limit: Constants.POST_LIMIT
        };
        // GET THE PAGE LIST
        const pagePostsResponse = await this.getAxios(pageUrl, headers, params);
        if (savePage) {
            const savePosts = [];
            const socialPosts = [];
            for (const post of pagePostsResponse.data) {
                const [userId, postId] = post.id.split("_");
                let link = `https://www.facebook.com/${userId}/posts/${postId}/`;
                savePosts.push({
                    users: authUser,
                    socialMedia: socialMedia,
                    facebookPages: savePage,
                    message: post.message || "",
                    thumbnails: post.full_picture || "",
                    like_counts: post.reactions.summary.total_count,
                    comment_count: post.comments.summary.total_count,
                    post_url: link,
                    post_id: post.id,
                    created_time: moment(post.created_time).format('YYYY-MM-DD HH:mm:ss')
                });
                socialPosts.push({
                    users: authUser,
                    socialMedia: socialMedia,
                    title: post.message || "",
                    description: "",
                    post_id: post.id,
                    image_url: post.full_picture || "",
                    social_type: SocialType.FACEBOOK,
                    post_url: link,
                    like_count: post.reactions.summary.total_count,
                    comment_count: post.comments.summary.total_count,
                    created_time: moment(post.created_time).format('YYYY-MM-DD HH:mm:ss')
                })
            }
            await this.FacebookPosts.save(savePosts);
            await this.SocialMediaPosts.save(socialPosts);
        }
    }

    /**
     * Saves a social media account to the user's profile.
     * 
     * @param request - An instance of SocialMediasDto containing the social media account's id and type.
     * @param authUser - The authenticated user object performing the link action.
     * 
     * @throws HttpException - Throws a 404 error if the user does not exist.
     * @throws HttpException - Throws a 400 error if the social media account already exists.
     * @throws HttpException - Throws a 400 error if the social media type is invalid.
     * 
     * After linking, the user's total followers and following counts are increased accordingly.
     */
    async saveSocialMedia(request, authUser) {
        const lang = authUser.language || 'en';
        const socialMediaExists = await this.SocialMedias.findOne({
            where: {
                users: { id: Not(authUser.id), deleted_at: IsNull() },
                social_user_name: request.social_user_name,
                social_type: request.social_media_type,
                is_verified: true
            }
        })
        if (socialMediaExists) {
            throw new HttpException(responseMessages[lang].user.social_media.arealy_exists, HttpStatus.RESET_CONTENT);
        }

        const save = await this.SocialMedias.save({
            users: authUser,
            social_id: request.social_id,
            social_type: request.social_media_type,
            social_access_token: request.access_token,
            social_user_name: request.social_user_name,
            refresh_token: request.refresh_token,
            source_posts_from: 'facebook',
            is_verified: true,
            missing_permissions: request.missing_permissions ?? []
        });
        // UNLINK UNVERIFIED SOCIAL MEDIA
        const unlinkUnverifiedSocialMedia = await this.SocialMedias.findOne({ where: { users: { id: authUser.id }, social_type: request.social_media_type, is_verified: false } })
        if (unlinkUnverifiedSocialMedia) {
            this.unlinkFacebook(unlinkUnverifiedSocialMedia);
        }
        return save;
    }
    /**
     * Refreshes the Facebook page access token for a social media account.
     * This function is a cron job that runs every *****.
     */
    async refreshToken(refresh_token) {
        const pageUrl = process.env.FACEBOOK_BASE_URL + 'oauth/access_token';
        const FACEBOOK_SECRET_KEY = await this.encryptionService.decrypt(process.env.FACEBOOK_SECRET_KEY);
        const FACEBOOK_CLIENT_ID = await this.encryptionService.decrypt(process.env.FACEBOOK_CLIENT_ID);
        const headers = {};
        const params = {
            grant_type: 'fb_exchange_token',
            client_id: FACEBOOK_CLIENT_ID,
            client_secret: FACEBOOK_SECRET_KEY,
            fb_exchange_token: refresh_token
        };
        // REFRESH TOKEN API
        return await this.getAxios(pageUrl, headers, params);
    }

    async facebookEdit(request, id) {

        const facebookPage = await this.FacebookPages.findOne({ where: { id: id } });
        if (!facebookPage) {
            throw new HttpException(responseMessages.en.user.social_media.not_exists, HttpStatus.RESET_CONTENT);
        }

        facebookPage['description'] = request.bio;
        facebookPage['name'] = request.name;
        facebookPage['city'] = request.city;
        facebookPage['country'] = request.country;
        facebookPage['gender'] = request.gender;

        this.FacebookPages.save(facebookPage)
        return;
    }

    /**
     * Unlinks a facebook account from the user's profile.
     * 
     * @param socialMedia - The social media account object to unlink.
     * 
     * @throws HttpException - Throws a 404 error if the social media account does not exist.
     */
    async unlinkFacebook(socialMedia) {
        await this.FacebookPosts.softDelete({ socialMedia: { id: socialMedia.id } });
        await this.FacebookPages.softDelete({ socialMedia: { id: socialMedia.id } });
        await this.SocialMediaPosts.softDelete({ socialMedia: { id: socialMedia.id } });
        await this.SocialMedias.softDelete({ id: socialMedia.id });
    }

    async getFacebookPosts(postId) {
        return this.FacebookPosts.find({ where: { facebookPages: { id: postId } }, order: { created_time: 'DESC' } });
    }

    /**
     * Syncs the Facebook page data of all social media accounts which are of type facebook.
     * This function is a cron job that runs every *****.
     */
    async syncFacebookPage(pageSize, social_id = null) {


        const headers = { 'Content-Type': 'application/json' };
        const params = {};
        const daysAgo = moment().subtract(Constants.SOCIAL_MEDIA_CRON_DAY, 'days').toDate();

        let query = await this.SocialMedias.createQueryBuilder('sm')
            .select(['sm.id', 'sm.social_user_name', 'sm.created_at'])
            .where('social_type = :social_type', { social_type: SocialType.FACEBOOK })
            .andWhere('(sm.updated_by_cron <= :dateLimit OR sm.updated_by_cron IS NULL)', {
                dateLimit: daysAgo
            })
            .andWhere('is_verified = true').andWhere('is_token_expire = false')

        // UPDATE SINGLE RECORD
        if (social_id) {
            query.andWhere('sm.id = :social_id', { social_id })
        }

        const [result, total] = await query.orderBy('sm.created_at', 'ASC').take(pageSize).getManyAndCount();
        if (result.length) {
            for (let socialMedia of result) {
                const facebookPages = await this.FacebookPages.find({ relations: ['users'], where: { socialMedia: { id: socialMedia.id } } });
                let total_followers = 0;
                for (let page of facebookPages) {
                    const pageUrl = process.env.FACEBOOK_BASE_URL + page.facebook_page_id;
                    const headers = {
                        Authorization: `Bearer ${page.access_token}`,
                    };
                    const params = {
                        fields: 'id,name,fan_count,followers_count,category,description,website,phone,location,emails,cover,picture,username,link,access_token',
                    };
                    console.log("FACEBOOK PAGE URL", pageUrl)
                    const pageDetailResponse = await this.getAxios(pageUrl, headers, params);
                    if (pageDetailResponse) {

                        page.description = pageDetailResponse.description || "", // Maps the description field
                            page.name = pageDetailResponse.name || "", // Maps the page name
                            page.emails = pageDetailResponse.emails ? pageDetailResponse.emails.join(', ') : "", // Join emails into a single string
                            page.page_logo = pageDetailResponse.picture?.data?.url || "", // Get page logo URL
                            page.cover_image = pageDetailResponse.cover?.source || "", // Get cover image URL
                            page.phone = pageDetailResponse.phone || "", // Maps the phone number
                            page.website = pageDetailResponse.website || "", // Maps the website URL
                            page.category = pageDetailResponse.category || "", // Maps the category field
                            page.fan_count = pageDetailResponse.fan_count || 0, // Maps the fan count
                            page.followers_count = pageDetailResponse.followers_count || 0, // Maps the followers count
                            page.city = pageDetailResponse.location?.city || "", // Maps the city
                            page.country = pageDetailResponse.location?.country || "", // Maps the country
                            page.latitude = pageDetailResponse.location?.latitude?.toString() || "", // Converts latitude to string
                            page.longitude = pageDetailResponse.location?.longitude?.toString() || "", // Converts longitude to string
                            page.street = pageDetailResponse.location?.street || "", // Maps the street address
                            page.zip = pageDetailResponse.location?.zip || "", // Maps the zip code

                            total_followers += pageDetailResponse.followers_count;
                        await this.FacebookPages.save(page)
                        await this.getFacebookPagePost(page, socialMedia, page.users)
                    } else {
                        this.SocialMedias.update({ id: socialMedia.id }, { apify_data_updated_attempts: socialMedia.apify_data_updated_attempts + 1 });
                        if (socialMedia.apify_data_updated_attempts >= 3) {
                            this.SocialMedias.update({ id: socialMedia.id }, { is_token_expire: true, updated_by_cron: moment().format('YYYY-MM-DD HH:mm:ss') });
                        }
                    }
                }
                // UPDATE SOCIAL MEDIA TABLE
                socialMedia = await this.SocialMedias.findOne({ where: { id: socialMedia.id } });
                socialMedia.follower_count = String(total_followers);
                socialMedia.source_posts_from = 'facebook';
                socialMedia.updated_by_cron = moment().format('YYYY-MM-DD HH:mm:ss');
                await this.SocialMedias.save(socialMedia);
            }
            if (total) {
                await this.syncFacebookPage(pageSize);
            }
        }
    }



    /**
     * Refreshes the access token of a social media account and all its associated pages.
     */
    async socialMediaRefreshToken(socialMedia) {
        try {
            const refreshToken = await this.refreshToken(socialMedia.refresh_token);
            if (refreshToken) {
                socialMedia.social_access_token = refreshToken.access_token;
                socialMedia.is_token_expire = false;
                socialMedia.access_token_expire_at = moment().add(55, 'days').format('YYYY-MM-DD')
                await this.SocialMedias.save(socialMedia);
                const facebookPage = await this.FacebookPages.find({ where: { socialMedia: { id: socialMedia.id } } });
                if (facebookPage) {
                    for (let page of facebookPage) {
                        const pageToken = await this.refreshToken(page.access_token);
                        if (pageToken) {
                            page.access_token_expire_at = moment().add(55, 'days').format('YYYY-MM-DD');
                            page.access_token = pageToken.access_token;
                            page.is_token_expire = false;
                            this.FacebookPages.save(page);
                        } else {
                            page.is_token_expire = true;
                            await this.FacebookPages.save(page);
                        }
                    }
                }
                return;
            }
            socialMedia.is_token_expire = true;
            await this.SocialMedias.save(socialMedia);
        } catch (error) {
            console.log(error.message);
        }

    }

    /**
     * Performs a GET request to the provided URL with the given headers and
     * parameters.
     *
     * @param {string} url - The URL to request.
     * @param {Object} headers - The headers to include in the request.
     * @param {Object} params - The query parameters to include in the request.
     *
     * @returns {Object} The response data from the request.
     *
     * @throws {HttpException} If the request fails, an HTTP exception is
     * thrown with the error message and a 400 status code.
     */
    async getAxios(url, headers, params) {
        try {
            const response = await axios.get(url, {
                headers: headers,
                params: params,
            });
            // Handle the response data
            return response.data;

        } catch (error) {
            console.log(error);
            return false;
        }
    }

}
