// eslint-disable-next-line no-unused-vars
import { Commit } from 'vuex'
import * as T from '../../utils/types.js'
import moment from 'moment'

/**
 *
 * Load Cached
 *
 * load the data cached, if the loading is triggered within the cache period, it will not return false
 *
 * @param commit
 * @param getters
 * @param data
 */
export const loadCached = function(
  {
    commit,
    getters,
  }: {
    commit: Commit
    getters: any
  },
  data: {
    payload: { [s: string]: any }
    loaderName: string
    expiresIn?: Date
  }
): Promise<boolean> {
  if (!data.expiresIn) {
    data.expiresIn = moment()
      .add(15, 'minute')
      .toDate()
  }

  let loadedData = getters.getCachedLoad(data.loaderName, data.payload)

  if (!loadedData || loadedData.expiresIn < new Date()) {
    // getters.cacheLoads
    commit(T.SET_CACHED_LOADING, {
      name: data.loaderName,
      payload: data.payload,
      expiresIn: data.expiresIn,
    })

    let promise = new Promise<boolean>(function(resolve: any) {
      commit(T.PROCESSING_STARTED, data.loaderName)
      resolve(true)
    })

    promise.finally(function() {
      commit(T.PROCESSING_FINISHED, data.loaderName)
    })

    return promise
  }

  return Promise.resolve(false)
}
