const moment  = require('moment')
const cleanDeep = require('clean-deep')
const Datastore = require('nedb-promises')
 renameKey = require('deep-rename-keys');
function isJSON(vl){

    if(typeof vl==="object") return true 

    return false
 
}


 async function filterDataOnComputed(options={
    data:[],
    filter:{},
    model:null,
    config:null,
}) {

   
    var db = Datastore.create();
    var arrayData  = []

    var filter  = cleanDeep(options.filter)||null
    var search = filter?.filterOnComputed||null
    search = cleanDeep(search)

    if(Object.keys(search).length && options.model && search){
        await db.insert(options.data)
        var newQueryFilter =renameKey(search,(key)=>{
            if(key=='in') return '$in'
            if(key=='notIn') return '$nin'
            if(key=='lt') return '$lt'
            if(key=='lte') return '$lte'
            if(key=='gt') return '$gt'
            if(key=='gte') return '$gte'
            if(key=='regex') return '$regex'

        })
        //

        arrayData = await db.find(newQueryFilter).then(e=>e).catch(err=>[])
        db.deleteMany({},{multi:true})


    }  else {
        arrayData = options.data || []
    }

    //console.log(arrayData)

    return arrayData
}


module.exports ={
    filterDataOnComputed
}