import notification from 'antd/lib/notification';

export default class Service {
    
    static call(settings) {
        const {url, method, body, setData, setLoading, errorTitle, errorMessage} = settings;

        const errors = {};

        if (!url || url == '') {
            errors['url'] = 'Required!';
        };

        if (!setData) {
            errors['setData'] = 'Required!';
        };

        if (!setLoading) {
            errors['setLoading'] = 'Required!';
        };

        if (Object.keys(errors).length > 0) {
            return console.error("Service call invalid setting:", errors);
        }

        setLoading(true);
        const fail = ()=> {
            setLoading(false);
            notification["error"]({
                message: errorTitle ? errorTitle : 'Erro no serviço',
                description: errorMessage ? errorMessage : url,
                style: {
                    marginTop: 100,
                }
            });
        };
        netuno.service({
            url: `/services/${url}`,
            method: method ? method.toUpperCase() : 'GET',
            credentials: 'include',
            headers: {
                'Content-Type': 'application/json'
            },
            body: body ? body : null,
            success: (response)=> {
                if (response.json) {
                    setData(response.json);
                    setLoading(false);
                } else {
                    fail();
                }
            },
            fail: ()=> {
                fail();
            }
        });   

    }

}