export default class Request {

    static async get(url) {
        const request = await fetch(`${url}&time=${Date.now()}`, {
            method: 'GET',
            cache: 'no-store'
        });

        return await request.text();
    }

    static async post(url, data, isFile) {
        const body = await this.getBody(data, isFile);
        const response = await fetch(url, {
            method: 'POST',
            cache: 'no-cache',
            body: body
        });
        if (response.status != 200) {
            throw response;
        }

        return await response.text();
    }

    static async appendToken(formData) {
        const token = Joomla.getOptions('csrf.token')

        formData.append(token, '1');
    }

    static async getBody(data, isFile) {
        const formData = new FormData();
        await this.appendToken(formData)
        if (!data) {
            return formData;
        }

        for (let ind in data) {
            if (Array.isArray(data[ind])) {
                data[ind].forEach(v => {
                    formData.append(`${ind}[]`, v);
                })
            } else if (!isFile && typeof data[ind] == 'object') {
                for (let i in data[ind]) {
                    formData.append(`${ind}[${i}]`, data[ind][i]);
                }
            } else {
                formData.append(ind, data[ind]);
            }
        }

        return formData;
    }
}