/**
 * Created by Tony on 2017/3/24.
 */
let mongoose = require('mongoose');
//let rpt_cfg_mdl = mongoose.model('rpt_cfg');

let cache = require('../../../public/cache/cacheUtil');
//let Rpt_Cfg_Mdl = require('../models/rpt_cfg');
let Rpt_Cfg_Mdl = mongoose.model('rpt_cfg');

const RPT_CFG_GRP = 'rpt_cfg';

module.exports = {
    setReportDefaultCache: function () {
        Rpt_Cfg_Mdl.find({userId: "Administrator"}, '-_id', function(err, cfgs){
            if(cfgs.length){
                cache.setCache(RPT_CFG_GRP,'admin_cfg',cfgs[0]);
            }
        })
    },
    getReportDefaultCache: function () {
        let rst = {ctrls: null, fonts: null, styles: null},
            admin_cfg = cache.getCache(RPT_CFG_GRP,'admin_cfg');
            ;
        rst.ctrls = admin_cfg.formats;
        rst.fonts = admin_cfg.fonts;
        rst.styles = admin_cfg.borders;
        admin_cfg = null;
        return rst;
    },
    setReportCacheByUser: function (userId) {
        let me = this;
        let user_cfg = cache.getCache(RPT_CFG_GRP,userId + '_cfg');
        if (!(user_cfg)) {
            Rpt_Cfg_Mdl.find({userId: userId}, '-_id', function(err, cfgs){
                if(cfgs.length){
                    cache.setCache(RPT_CFG_GRP, userId + '_cfg',cfgs[0]);
                } else {
                    me.setReportDefaultCache();
                }
            })
        }
    },
    getReportCacheByUser: function (userId, cb) {
        let me = this,
            rst = {ctrls: null, fonts: null, styles: null},
            user_cfg = cache.getCache(RPT_CFG_GRP,userId + '_cfg');
        ;
        if (!(user_cfg)) {
            Rpt_Cfg_Mdl.find({userId: userId}, '-_id', function(err, cfgs){
                if(cfgs.length){
                    cache.setCache(RPT_CFG_GRP, userId + '_cfg',cfgs[0]);
                    user_cfg = cache.getCache(RPT_CFG_GRP,userId + '_cfg');
                    rst.ctrls = user_cfg.formats;
                    rst.fonts = user_cfg.fonts;
                    rst.styles = user_cfg.borders;
                    user_cfg = null;
                    cb(rst);
                } else {
                    user_cfg = null;
                    cb(me.getReportDefaultCache());
                }
            })
        } else {
            rst.ctrls = user_cfg.formats;
            rst.fonts = user_cfg.fonts;
            rst.styles = user_cfg.borders;
            user_cfg = null;
            cb(rst);
        }
    }
}
