import axios from 'axios'
import { NetworkProxy } from './typings'
import CfExceptionHandler from "../../core/CfExceptionHandler";

export default class CfNetwork implements NetworkProxy{
    private config

    constructor(key: string) {

        this.config = {
            headers: {
                'Authorization': `Bearer ${key}`
            }
        }
    }

    public async get(url:string):Promise<Object> {
        try {
            const fetchedData = (await axios.get(`${url}`, this.config)).data

            return fetchedData

        } catch (e) {
            console.error('Error retrieving data: ', e)

            if(url.includes("nudge")){
                new CfExceptionHandler().throwNudgeFetchError('nudge fetch API',e.toString())
            }else{
                new CfExceptionHandler().throwAndLogError('API Error', e.toString())
            }
        }
    }

    public async send(url:string, payload: any):Promise<Object> {
        try {
            const postData = (await axios.post(url, payload, this.config)).data
            return postData
        } catch(error) {
            if(!url.includes("sdk/crash")){
                new CfExceptionHandler().throwAPIError('API Error',
                    `URL: ${url}\n\nerror.response: ${error.response.toString()}\n\nerror.response.data: ${error.response.data}`)
            }
            throw error;
        }
    }

}
