import axios from 'axios';
import Utils from '@/lib/Utils';

const $ax = axios.create({
    baseURL: '/api/',
    transformRequest: [
        (data, headers)=>{
            if (data && !(data instanceof FormData)){
                data = Utils.deepMerge({}, data, (k, v)=>{
                    return k.startsWith('__') ? undefined : v;
                })
                data = JSON.stringify(data);
                headers['Content-Type'] = 'application/json;charset=utf-8';
            }
            return data;
        }
        , ...axios.defaults.transformRequest
    ]
})

export default {
    install: (app, options) => {
        app.config.globalProperties.$api = {
            gameObject:{
                async save(data){
                    return await $ax.put('/game-object', data);
                },
                async load(id){
                    return await $ax.get(`/game-object/${id}`);
                },
                async search(query){
                    return await $ax.post('/game-object', query);
                },
                async remove(id){
                    return await $ax.delete(`/game-object/${id}`)
                }
            },
            scenario:{
                async save(data){
                    return await $ax.put('/scenario', data);
                },
                async load(id){
                    return await $ax.get(`/scenario/${id}`);
                },
                async search(query){
                    return await $ax.post('/scenario', query);
                },
                async remove(id){
                    return await $ax.delete(`/scenario/${id}`)
                }
            },
            game:{
                async save(data){
                    return await $ax.put('/game', data);
                },
                async load(id){
                    return await $ax.get(`/game/${id}`);
                },
                async search(query){
                    return await $ax.post('/game', query);
                },
                async remove(id){
                    return await $ax.delete(`/game/${id}`)
                }
            }
        }
    }
}