import {  put,  call, select, take } from 'redux-saga/effects'
import createAxiosRequestChannel from '../../services/WithSagaAxiosInstance'
import {getAccessToken } from '../user/selectors'
import {MettaSvr_Common} from './action-enums'
import {UserActionTypes} from '../user/action.types'

// Todo: handle 401
//            ex.response.status === 401 ?
// dispatch(postForgotPasswordFailure( `${ex.response.data}: ${ex.message}`)):


export function* handleODataChannelCallbacks(config, successCb, failureCb){
    const { CountKey, ValueKey } = MettaSvr_Common.ODATA_Keys
    const token = yield select(getAccessToken)

    const fetchChannel = yield call(createAxiosRequestChannel,token, config)

    try{
        while(true){
            const output = yield take(fetchChannel)
            const {crt, response, err, message, statusCode} = output
            if(!!crt){
            yield put({
                    type: UserActionTypes.UPDATE_ACCESS_TOKEN,
                    payload: crt
                })

            }

            if(!!response){
                yield put(successCb({records: response.data[ValueKey],count: response.data[CountKey]}))
            }

            if(!!err){

                if(statusCode === 401){
                    yield put(failureCb({message: `${message}. Please Re-Login`}));
                }else{
                    yield put(failureCb({message}));
                }
            }
            
        }
    }
    catch(err){
        console.log("🚨  fetch / post failed ", err)
        yield put(failureCb({message:err.response.data}));
    }
    finally{
        fetchChannel.close()
    }
}

export function* handleGeneralChannelCallbacks(config, successCb, failureCb){
    const token = yield select(getAccessToken)

    const fetchChannel = yield call(createAxiosRequestChannel,token, config)

    try{
        while(true){
            const output = yield take(fetchChannel)

            const {crt, response,  err, message, statusCode} = output
            if(!!crt){
            yield put({
                    type: UserActionTypes.UPDATE_ACCESS_TOKEN,
                    payload: crt
                })

            }

            if(!!response){
                const {apiResponseStatus, errorMessage, result } = response.data
                if (apiResponseStatus === MettaSvr_Common.APIResponseStatus.Error){
                    yield put(failureCb({message: errorMessage, apiResponseStatus}))
                }else{
                    console.log('success ', result)
                    yield put(successCb(result))
                }
            }

            if(!!err){

                if(statusCode === 401){
                    yield put(failureCb({message: `${message}. Please Re-Login`}));
                }else{
                    yield put(failureCb({message}));
                }
            }
            
        }
    }
    catch(err){
        console.log("🚨  fetch / post failed ", err)
        yield put(failureCb({message:err.response.data}));
    }
    finally{
        fetchChannel.close()
    }
}