const moment = require('moment')
const cacheModels  ={


}


function updateCacheChanged(model,config){
        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){
      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
}