import { takeLatest,  all, call, select } from 'redux-saga/effects'
import buildQuery from 'odata-query'
import LabReportActionTypes from './lab-report.action.types'
import { getCurrentUserId} from './selectors'
import {METADATA_END_POINTS} from '../../helpers/action-urls'
import {MettaSvr_Common} from '../../helpers/action-enums'
import { handleGeneralChannelCallbacks, handleODataChannelCallbacks } from '../../helpers/common-sagas'
import {fetchLabReportListSuccess, labReportListFailure, createLabReportSuccess,
  downloadLabReportSuccess, downloadLabReportFailure
} from './lab-report.action'




export function* fetchLabReportListAsync({payload}){
      // console.log('lab report before fetching ', payload)
      const { page, patientId, numOfRecords} = payload
      const currentUserId = yield select(getCurrentUserId) //only when patient logs in
      const { GET_LAB_REPORT_LIST } = METADATA_END_POINTS.patient
      const nRecords = numOfRecords ?? MettaSvr_Common.ITEMS_PER_PAGE
      const odataQuery = {
          top: nRecords,
          skip: nRecords * (page - 1),
          count: true,                   
      }

      const query = buildQuery( odataQuery )
      const config = {
        url: `${GET_LAB_REPORT_LIST(patientId ?? currentUserId)}${query}`
      }


      yield call(handleODataChannelCallbacks, config, fetchLabReportListSuccess, labReportListFailure)
  
}

export function* createLabReportStartAsync({payload}){
      const { REGISTER_LAB_REPORT, API_VERSION_V1 } = METADATA_END_POINTS.patient
      const config = {
        url: `${API_VERSION_V1}${REGISTER_LAB_REPORT}`,
        method: 'post',
        data: payload
      }

      yield call(handleGeneralChannelCallbacks, config, createLabReportSuccess, labReportListFailure)
  
}

export function* fetchDownloadLabReportStartAsync({payload}){

    const { page, patientId, numOfRecords, columns = []} = payload
    const currentUserId = yield select(getCurrentUserId) //only when patient logs in

    const odataQuery = {
      // top: numOfRecords,
      // skip: numOfRecords * (page - 1),                
      count: true,
    // orderBy: [`${sortColumn} ${sortOrder}`]
    }

/*
Select clause doent work in v4 odata query..
    if(columns.length > 0){
      odataQuery["select"] = columns
    }
*/
    var extraQuery = null 
    if(!!patientId) {
        extraQuery = {
            ...odataQuery,
            filter: {
                PatientId: { eq: { type: 'guid', value: patientId ?? currentUserId } },
            },
        }
    }
    const query = buildQuery( extraQuery ?? odataQuery )


    const { PATIENT_LAB_REPORT } = METADATA_END_POINTS.common
    const config = {
      url: `${PATIENT_LAB_REPORT}${query}`,
    }

    yield call(handleODataChannelCallbacks, config, downloadLabReportSuccess, downloadLabReportFailure)
  
}

//listeners
export function* onFetchLabReportListStart(){
  yield takeLatest(LabReportActionTypes.FETCH_LAB_REPORT_START, fetchLabReportListAsync)
}

export function* onLabReportCreateStart(){
  yield takeLatest(LabReportActionTypes.CREATE_LAB_REPORT_START, createLabReportStartAsync)
}

export function* onLabReportDownloadStart(){
  yield takeLatest(LabReportActionTypes.DOWNLOAD_LAB_REPORT_START, fetchDownloadLabReportStartAsync)
}

//final visitor sagas shared
export function* labReportSagas() {
    yield all([
      call(onFetchLabReportListStart),      
      call(onLabReportCreateStart),
      call(onLabReportDownloadStart)
    ])
  }