import { get, post, uploader } from '../../utils/api'
import {
  PROCESSING_FINISHED,
  PROCESSING_STARTED,
  SET_UPLOAD_SETTINGS,
  SET_UPLOADS,
  CLEAR_LOADED_DATA,
} from '../../utils/types'
import { API_UPLOAD, API_UPLOAD_SETTINGS } from '../../utils/apiUrls'
import { PRINT_PAGE } from '@/store/utils/localStorageKeys'
import * as T from '../../utils/types'
import * as U from '../../utils/apiUrls'
import queryString from 'querystring'

export const getUploadSettings = ({ commit }, query) => {
  return post(API_UPLOAD_SETTINGS, query).then(response => {
    commit(SET_UPLOAD_SETTINGS, response.data)
  })
}

export const doUpload = ({ commit, dispatch }, form) => {
  let uploaderName = form.get('uploader_name', name)
  form.delete('uploader_name')
  commit(PROCESSING_STARTED, 'uploading-' + uploaderName, { root: true })
  commit(PROCESSING_STARTED, 'uploading', { root: true })
  return uploader(API_UPLOAD, form)
    .then(response => {
      if (response.data && response.data.hasOwnProperty('file')) {
        // Incorrect file type
        return { error: response.data.file[0] }
      }
      commit(SET_UPLOADS, response.data)
      return true
    })
    .catch(e => {
      dispatch('logError', { image_upload_failed: e.data }, { root: true })
      return false
    })
    .finally(() => {
      commit(PROCESSING_FINISHED, 'uploading', { root: true })
      commit(PROCESSING_FINISHED, 'uploading-' + uploaderName, { root: true })
    })
}

export const setPrintData = (store, payload) => {
  localStorage.setItem(PRINT_PAGE + payload.key, JSON.stringify(payload.data))
}

export const retrievePrintData = (store, key) => {
  return JSON.parse(localStorage.getItem(PRINT_PAGE + key))
}

export const removePrintData = (store, key) => {
  localStorage.removeItem(PRINT_PAGE + key)
}

export const clearShoppingData = ({ dispatch }, exclude = []) => {
  return dispatch(
    'clearLoadedData',
    ['sales', 'products', 'cart', 'focpwp', 'order', 'cv-wallet', 'autoship', 'iToken'].filter(
      f => !exclude.includes(f)
    )
  )
}

export const clearLoadedData = ({ commit }, payload) => {
  ;['', 'enrolment/', 'eshop/', 'myBundle/', 'itoken/'].forEach(function(namespace) {
    if (Array.isArray(payload)) {
      payload.forEach(type => {
        commit(namespace + CLEAR_LOADED_DATA, type)
      })
    } else {
      commit(namespace + CLEAR_LOADED_DATA, payload)
    }
  })
}

export const checkMemberCrossSponsoringStatus = async ({ commit, getters, dispatch }, payload = {}) => {
  commit(T.PROCESSING_STARTED, 'classicCrossSponsoringVerification', { root: true })
  commit(T.RESET_CLASSIC_CROSS_SPONSORING_VERIFICATION)
  let cancelToken = await dispatch('generateCancelToken', 'classicCrossSponsoringVerification', { root: true })

  let query = `?${queryString.stringify({
    sponsor_user_id: payload.sponsorId,
    prospect_ic_passport_number: payload.applicantIcPassportNumber,
  })}`

  return await get(U.API_CROSS_SPONSORING_VERIFICATION_CHECK + query, cancelToken.token)
    .then(response => {
      commit(T.SET_CLASSIC_CROSS_SPONSORING_VERIFICATION, response.data)
      commit(T.PROCESSING_FINISHED, 'classicCrossSponsoringVerification', { root: true })
      return response.data && response.data.result
    })
    .catch(() => {
      commit(T.RESET_CLASSIC_CROSS_SPONSORING_VERIFICATION)
      commit(T.PROCESSING_FINISHED, 'classicCrossSponsoringVerification', { root: true })
      return false
    })
}

export const getUserOnDemandVerification = async ({ commit, getters, dispatch }, payload = {}) => {
  commit(T.PROCESSING_STARTED, 'userOnDemandVerification', { root: true })
  commit(T.RESET_ON_DEMAND_VERIFICATION)
  let cancelToken = await dispatch('generateCancelToken', 'userOnDemandVerification', { root: true })
  if (payload.value !== '') {
    return post(U.API_GET_USER_ONDEMAND_VERIFICATION, payload, cancelToken.token)
      .then(response => {
        commit(T.SET_ON_DEMAND_VERIFICATION, response.data)
        commit(T.PROCESSING_FINISHED, 'userOnDemandVerification', { root: true })
      })
      .catch(() => {
        commit(T.RESET_ON_DEMAND_VERIFICATION)
        commit(T.PROCESSING_FINISHED, 'userOnDemandVerification', { root: true })
      })
  } else {
    commit(T.RESET_ON_DEMAND_VERIFICATION)
    commit(T.PROCESSING_FINISHED, 'userOnDemandVerification', { root: true })
  }
}

export const setIcPassportValidation = ({ commit }, payload) => {
  commit(T.SET_IC_PASSPORT_VALIDATION, payload)
}

export const setAutoValidationTrigger = ({ commit }) => {
  commit(T.SET_AUTO_VALIDATION_TRIGGER_STATUS)
}

export const setExperimentalFeature = ({ commit }, payload) => {
  commit(T.SET_EXPERIMENTAL_FEATURE, payload)
}

export const loadHierarchicalConfig = async ({ commit }, key) => {
  commit(T.PROCESSING_STARTED, 'loadingHierarchicalConfig')
  let query = '?' + queryString.stringify({ lookup: key })

  return await get(U.API_GET_HIERARCHICAL_CONFIG + query)
    .then(response => response.data)
    .catch(() => false)
    .finally(() => {
      commit(T.PROCESSING_FINISHED, 'loadingHierarchicalConfig')
    })
}
