/* global uba_elsPermission */
// eslint-disable-next-line camelcase
const me = uba_elsPermission
const UB = require('@unitybase/ub')
const { LocalDataStore } = require('@unitybase/cs-shared')
const App = UB.App

me.entity.addMethod('select')

/**
 * Return all entities methods with their access rights for specified roles set
 *
 * @method select
 * @memberOf uba_elsPermission_ns.prototype
 * @memberOfModule @unitybase/uba
 * @param {ubMethodParams} ctx
 * @param {UBQL} ctx.mParams ORM query in UBQL format
 * @param {Array<number>} ctx.mParams.whereList.roles.value
 * @published
 * @return {Boolean}
 */
me.select = function (ctx) {
  const permissionsFieldList = ['ID', 'entity', 'method', 'hasAccess']
  const roleIDs = ctx.mParams.forRoles
  ctx.dataStore.currentDataName = 'select'

  let filteredData
  if (!Array.isArray(roleIDs)) {
    console.error('uba_elsPermission.select expect forRoles parameter passed in misc')
    filteredData = { resultData: { data: [] } }
  } else if (roleIDs.length) {
    const permissions = permissions4Roles(roleIDs)
    filteredData = LocalDataStore.doFilterAndSort({
      data: permissions,
      fields: permissionsFieldList,
      rowCount: permissions.length
    }, ctx.mParams)
  } else {
    filteredData = { resultData: { data: [] } }
  }

  // return fields in order they are requested
  const requestedFieldList = ctx.mParams.fieldList
  const fieldMapping = []
  requestedFieldList.forEach(f => {
    fieldMapping.push({
      from: permissionsFieldList.indexOf(f),
      to: f
    })
  })
  ctx.dataStore.initialize(filteredData.resultData.data, fieldMapping)
  ctx.dataStore.totalRowCount = filteredData.resultData.data.length
  return true // everything is OK
}

function permissions4Roles (roleIDs) {
  const entities = App.domainInfo.entities
  const res = []
  let ID = 1
  for (const eCode in entities) {
    const e = entities[eCode]
    for (const mCode in e.entityMethods) {
      // res.push({
      //   ID: ID++,
      //   entity: eCode,
      //   method: mCode,
      //   hasAccess: App.els(eCode, mCode, roleIDs) ? 1 : 0
      // })
      res.push([ID++, eCode, mCode, App.els(eCode, mCode, roleIDs)]) //  ? 1 : 0
    }
  }
  return res
}