const nodecache =require('node-cache')
const moment = require('moment')
const sessionJwt = new nodecache({ stdTTL : 60*60*24*7});
const Datastore = require('@seald-io/nedb')
const cacheKeys = new Datastore({autoload:true,filename:'.tmp/tokens.db',timestampData:true})
const {createClient} =require("redis")
cacheKeys.ensureIndex({
    fieldName: 'createdAt',
    expireAfterSeconds: 60*60*24*7
  })
const cacheModels  ={


}


async function initRedisCache(config){
const rediscache = createClient({
    url:process.env.REDIS_URL
})

try{
    await rediscache.connect()
    config.caches = rediscache

    config.redis.isOk =true
    rediscache.on('error', err => console.log('Redis Client Error', err));
} catch(err){
    consola.error(` Error when try to connect to Redis server ${err}
    `)
}


}


function updateCacheChanged(model,config){
    model = model?.toLowerCase();
   
      if(model && !model.match(/(vcaches|modelviews)/)){
       
        //console.log('Cache changed for  ',model)
        var time = moment().format()
        if(cacheModels[model]){
            cacheModels[model] ={
                ...cacheModels[model],
                LastChanged:time,
            }
        } else {
            cacheModels[model] ={
                LastChanged:time,
                LastFind:moment(time).add(60,'milliseconds').format()
            }
        }
      }
       // console.log('Change mm',cacheModels[model],model)
}


function updateCachedQuery(model,config){
    model = model?.toLowerCase();
    if(model){
        var time = moment().format()
        cacheModels[model] ={
            ...cacheModels[model],
            LastFind:time
        }
        if(!cacheModels[model].LastChanged){
            cacheModels[model].LastChanged= moment(time).subtract(60,'milliseconds').format()
        }
    }
}

function canResolveCache(model,config){
    var canExit = false // Check relation
    var collection = config.getOneCollection(model)
    var collectionRelations =[]
    collection.fields.map(f=>{
        if(f.type=='relationship'){
            collectionRelations.push(f.relationTo)
        }
    })

    collectionRelations.map(model=>{
        let cacheModel_ = cacheModels[model] || null
        if(cacheModel_){
            canExit = moment(cacheModel_.LastChanged).isAfter(cacheModel_.LastFind,'milliseconds')
        }
    })

    if(canExit) return false


    var cacheModel = cacheModels[model] 
   // console.log(cacheModel,model)
    if(!cacheModel) return false
    var ChangeDetected =  (moment(cacheModel.LastChanged).isAfter(cacheModel.LastFind,'milliseconds'))

   //ChangeDetected ? console.log('Changed detected') :null
    return !ChangeDetected

}



module.exports ={
    updateCacheChanged,
    updateCachedQuery,
    canResolveCache,
    sessionJwt,
    cacheKeys,
    initRedisCache
}