import axios from 'axios'
import { eventChannel, END } from "redux-saga"
/**
 * token: accessToken to be sent along with the request
 * requestConfig should have min:
 * {
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default
    // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
 * 
 */

const createAxiosRequestChannel = (token, requestConfig) => {
    return eventChannel(emit => {

        const _axiosApiInstance = axios.create()

        // Request interceptor for API calls
        _axiosApiInstance.interceptors.request.use(
            config => {

                config.headers = { 
                    'Authorization': `Basic ${token}` 
                }
                return config;
            },
            error => {
                emit({err: new Error(error.message)})
                emit(END)            }
        )

        // Response interceptor for API calls
        _axiosApiInstance.interceptors.response.use((response) => {
            
            //if refresh token is present        
            const refresh_token = response.headers["crt"]
            if(!!refresh_token){            
                // console.log('the response ', refresh_token)
                emit({crt: refresh_token})
                // dispatch({
                //     type: UserActionTypes.UPDATE_ACCESS_TOKEN,
                //     payload: refresh_token
                // })
            }
            emit ({response})
            emit(END)
        }, (error) => {
            /*
            const originalRequest = error.config;
            if (error.response.status === 403 && !originalRequest._retry) {
            originalRequest._retry = true;
            const access_token = await refreshAccessToken();            
            axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
            return axiosApiInstance(originalRequest);
            }
            */
            emit({err: new Error(error.message), message: error.response.data, statusCode: error.response.status})
            emit(END)
        })

        _axiosApiInstance.request(requestConfig)
        const unsubscribe = () => {
            console.log('unsubscribed...🙏🏽')
        }
        return unsubscribe
    })

    
}


export default createAxiosRequestChannel