import axios from 'axios';
import qs from 'qs';
import {updateMessages} from '../actions/notification/notificationActions';
import {authActivity} from '../constants/authConstants';
import {notificationMessages} from '../constants/notificationConstants';
import {store} from '../configureStore';

const getAuthLocalToken = () => {
    return localStorage.accessToken || '';
}

const defaultParams = () => ({
    method: 'get',
    responseType: 'json',
    headers: getAuthLocalToken() !== '' ?
        {
            Authorization: 'Bearer ' + getAuthLocalToken()
        } :
        {

        }
});

const uploadParams = () =>({
    method: 'post',
    responseType: 'json',
    headers: {
        Authorization: 'Bearer ' + getAuthLocalToken(),
        'content-type': 'multipart/form-data'
    }
});

class HtmlClient {

    fetch(configParams) {
        if(configParams.data){
            configParams.data = qs.stringify(configParams.data);
        }
        const params = Object.assign({}, defaultParams(), configParams);
        authActivity.lastActivity = Date.now();

        return axios(params);
    };

    uploadFile(file, configParams = null) {
        let formData = new FormData();
        formData.append('file', file, file.name);

        if(configParams) {

            Object.keys(configParams.data).forEach((paramKey) => {
                formData.append(paramKey, configParams.data[paramKey]);
            });

        }
        configParams.data = formData;
        const params = Object.assign({}, uploadParams(), configParams);

        return axios(params);
    }

    onError(error) {
        const response = error.response;
        if (response && response.data && response.data.code) {
            switch (response.data.code) {
                case 'rest_missing_callback_param':
                    store.dispatch(updateMessages([{code:'error', message: response.data.message }]));
                    return;
                case 'rest_invalid_param':
                    const messages = Object.keys(response.data.data.params).map(paramName => {
                        const errorMessage = response.data.data.params[paramName];
                        if (errorMessage === 'Invalid parameter.') {
                            return { code: 'error', message: `Invalid ${paramName} parameter!` };
                        }
                        return { code: 'error', message: errorMessage };
                    });
                    store.dispatch(updateMessages(messages));
                    return;
            }
        }
        store.dispatch(updateMessages([{code:'error', message: 'HTML_ERROR'}], notificationMessages));
    }
}

export default HtmlClient;
