const system = require("../../../system");
const ServiceBase = require("../../sve.base");
var settings = require("../../../../config/settings");

class CacheService {
  constructor() {
    this.cacheManager = system.getObject("db.common.cacheManager");
  }
  async buildCacheRtn(pageValues) {
    var ps = pageValues.map(k => {
      var tmpList = k.split("|");
      if (tmpList.length == 2) {
        return { name: tmpList[0], val: tmpList[1], key: k };
      }
    });
    return ps;
  }
  async findAndCountAll(obj) {
    const pageNo = obj.pageInfo.pageNo;
    const pageSize = obj.pageInfo.pageSize;
    const limit = pageSize;
    const offset = (pageNo - 1) * pageSize;
    var search_name = obj.search && obj.search.name ? obj.search.name : "";

    var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
    var cacheList = await this.cacheManager["MagCache"].getCacheSmembersByKey(cacheCacheKeyPrefix);
    if (search_name) {
      cacheList = cacheList.filter(f => f.indexOf(search_name) >= 0);
    }
    var pageValues = cacheList.slice(offset, offset + limit);
    var kobjs = await this.buildCacheRtn(pageValues);
    var tmpList = { results: { rows: kobjs, count: cacheList.length } };
    return system.getResultSuccess(tmpList);
  }
  async delCache(obj) {
    var keyList = obj.del_cachekey.split("|");
    if (keyList.length == 2) {
      var cacheCacheKeyPrefix = "sadd_children_appkeys:" + settings.appKey + "_cachekey";
      await this.cacheManager["MagCache"].delCacheBySrem(cacheCacheKeyPrefix, obj.del_cachekey);
      await this.cacheManager["MagCache"].del(keyList[0]);
      return { status: 0 };
    }
  }
  async clearAllCache(obj) {
    await this.cacheManager["MagCache"].clearAll();
    return { status: 0 };
  }
}
module.exports = CacheService;
