import DOM from './dom.js';

export default class API {
    
    static getCsrfToken() {
        return document.querySelector(idCSRFToken).getAttribute('content');
    }
    
    static async request(hashEndpoint, method = 'GET', data = null, params = null) {
        const url = API.getUrlFromHash(hashEndpoint, params);
        const csrfToken = API.getCsrfToken();
        const options = {
            method,
            headers: {
                'Content-Type': 'application/json',
                [flagCsrfToken]: csrfToken,
            }
        };

        if (data && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
            data = { 
                ...data, 
                [flagCsrfToken]: csrfToken,
            };
            options.body = JSON.stringify(data);
        }

        try {
            const response = await fetch(url, options);
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            return await response.json();
        } catch (error) {
            console.error('API request failed:', error);
            throw error;
        }
    }
    
    static getUrlFromHash(hash, params = null) {
        if (hash == null) hash = hashPageHome;
        let url = API.parameteriseUrl(_pathHost + hash, params);
        return url;
    }
    static parameteriseUrl(url, params) {
        if (params) {
            url += '?' + new URLSearchParams(params).toString();
        }
        return url;
    }
    static goToUrl(url) {
        window.location.href = url;
    }
    static goToHash(hash, params = null) {
        const url = API.getUrlFromHash(hash, params);
        API.goToUrl(url);
    }

    // specific api calls
    /* Example:
    getUsers: () => request('/users'),
    getUserById: (id) => request(`/users/${id}`),
    createUser: (userData) => request('/users', 'POST', userData),
    updateUser: (id, userData) => request(`/users/${id}`, 'PUT', userData),
    deleteUser: (id) => request(`/users/${id}`, 'DELETE'),
    */

    // User
    // user
    static async loginUser() {
        let callback = {};
        callback[flagCallback] = DOM.getHashPageCurrent();
        return await API.request(hashPageUserLogin, 'POST', callback);
    }
    static async saveUsers(users, formFilters, comment) {
        let dataRequest = {};
        dataRequest[flagFormFilters] = DOM.convertForm2JSON(formFilters);
        dataRequest[flagUser] = users;
        dataRequest[flagComment] = comment;
        return await API.request(hashSaveUserUser, 'POST', dataRequest);
    }

    // MTG Game API methods
    static async getIsGameDataOutdated(game) {
        const url = `/mtg/api/game/${game[attrGameId]}/is-outdated`;
        let dataRequest = {};
        dataRequest[flagGame] = game;
        return await API.request(url, 'POST', dataRequest);
    }

    static async saveGame(game, formFilters, comment) {
        let dataRequest = {};
        dataRequest[flagFormFilters] = DOM.convertForm2JSON(formFilters);
        dataRequest[flagGame] = game;
        dataRequest[flagComment] = comment;
        return await API.request(hashSaveGame, 'POST', dataRequest);
    }

    static async getGamePlayers(gameId) {
        const url = `/mtg/api/game/${gameId}/players`;
        return await API.request(url, 'GET');
    }
    static async saveGamePlayers(players, formFilters, comment) {
        let dataRequest = {};
        dataRequest[flagFormFilters] = DOM.convertForm2JSON(formFilters);
        dataRequest[flagPlayer] = players;
        dataRequest[flagComment] = comment;
        return await API.request(hashSaveGamePlayer, 'POST', dataRequest);
    }

    static async getGameRounds(gameId) {
        const url = `/mtg/api/game/${gameId}/rounds`;
        return await API.request(url, 'GET');
    }

    static async getGameDamageRecords(gameId) {
        const url = `/mtg/api/game/${gameId}/damage-records`;
        return await API.request(url, 'GET');
    }
    static async saveGameRoundPlayerDamages(rounds, damages, formFilters, comment) {
        let dataRequest = {};
        dataRequest[flagFormFilters] = DOM.convertForm2JSON(formFilters);
        dataRequest[flagDamage] = damages;
        dataRequest[flagRound] = rounds;
        dataRequest[flagComment] = comment;
        return await API.request(hashSaveGameRoundPlayerDamage, 'POST', dataRequest);
    }


}
