/**
 * Created by Tony on 2017/3/17.
 */
var test = require('tape');
var mongoose = require('mongoose');
var JV = require('../../../modules/reports/rpt_component/jpc_value_define');
var Template = require('../../../modules/all_models/rpt_template');
var TemplateData = require('../../../modules/all_models/rpt_tpl_data_demo');
var JpcEx = require('../../../modules/reports/rpt_component/jpc_ex');
var rptUtil = require("../../../modules/reports/util/rpt_util");
var fs = require('fs');

test('test get report pages function: ', function (t) {
    rptUtil.setReportDefaultCache();
    t.pass('just pass for cache setup!');
    t.end();
});

test('test get report pages function: ', function (t) {
    var grp_id = "SC";
    var tpl_id = "08_2";
    var pageSize = "A4";
    var rptTpl = null, tplData = null;
    Template.getPromise(grp_id, tpl_id).then(function(rst) {
        //console.log(rst);
        rptTpl = rst;
        console.log(rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE]);
        t.equal(rptTpl != null, true);
        return TemplateData.getPromise(tpl_id);
    }).then(function(rst){
        //console.log(rst);
        tplData = rst;
        t.equal(tplData != null, true);
        if (tplData) {
            var printCom = JpcEx.createInit();
            rptTpl[JV.NODE_MAIN_INFO][JV.NODE_PAGE_INFO][JV.PROP_PAGE_SIZE] = pageSize;
            var defProperties = rptUtil.getReportDefaultCache();
            printCom.initialize(rptTpl);
            printCom.analyzeData(rptTpl, tplData, defProperties);
            var maxPages = printCom.totalPages;
            var pageRst = printCom.outputAsSimpleJSONPageArray(rptTpl, tplData, 1, maxPages, defProperties);
            if (pageRst) {
                //save as file
                var pageStr = JSON.stringify(pageRst);
                var buffer = new Buffer(pageStr);
                //var length = buffer.length;
                fs.writeFile('../../../tmp/' + tpl_id + '.page.txt',buffer,function(err){
                    if(err) throw err;
                    console.log('has finished');
                });
            }
            t.equal(pageRst != null, true);
        }
        t.end();
    }).catch(function (err) {
        console.log("err: " + err);
        t.end();
    })

});

test('finish', function (t) {
    mongoose.disconnect();
    t.pass('closing db connection');
    t.end();
});