var JV = require('./jpc_value_define');
var JE = require('./jpc_rte');
var JpcFieldHelper = require('./helper/jpc_helper_field');
var JpcBandHelper = require('./helper/jpc_helper_band');
var JpcBand = require('./jpc_band');
var JpcFlowTabHelper = require('./helper/jpc_helper_flow_tab');
var JpcCommonHelper = require('./helper/jpc_helper_common');
var JpcDiscreteHelper = require('./helper/jpc_helper_discrete');
var JpcTextHelper = require('./helper/jpc_helper_text');
var JpcCommonOutputHelper = require('./helper/jpc_helper_common_output');
var JpcAreaHelper = require('./helper/jpc_helper_area');

var JpcFlowTabSrv = function(){};
JpcFlowTabSrv.prototype.createNew = function(){
    function private_addPageValue(ValuedIdxLst, sortedSequence, preRec, nextRec,page_seg_map, segIdx, pageIdx) {
        var vIdx = [];
        for (var vi = 0; vi < nextRec; vi++) {
            if (sortedSequence.length > preRec + vi) {
                vIdx.push(sortedSequence[preRec + vi]);
            } else {
                vIdx.push(JV.BLANK_VALUE_INDEX);
            }
        }
        page_seg_map.push([pageIdx, segIdx]);
        ValuedIdxLst.push(vIdx);
    }
    var JpcFlowTabResult = {};
    JpcFlowTabResult.initialize = function() {
        var me = this;
        me.segments = [];
        me.dispValueIdxLst = [];
        me.page_seg_map = [];
        me.disp_fields_idx = [];
        me.seg_sum_fields_idx = [];
        me.seg_sum_tab_fields = [];
        me.page_sum_fields_idx = [];
        me.group_fields_idx = [];
        me.pageStatusLst = [];
        me.groupSumValLst = [];
        me.segSumValLst = [];
        me.multiCols = 1;
    };
    JpcFlowTabResult.sorting = function(rptTpl, dataObj, dataSeq) {
        var me = this;
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM][JV.PROP_SUM_FIELDS], me.seg_sum_tab_fields, me.seg_sum_fields_idx);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_PAGE_SUM][JV.PROP_SUM_FIELDS], null, me.page_sum_fields_idx);
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_GROUP][JV.PROP_GROUP_FIELDS], null, me.group_fields_idx);
        for (var si = 0; si < dataSeq.length; si++) {
            me.segments.push(dataSeq[si].slice(0));
        }
        //pre-sum the data(for seg sum display)
        var data_details = dataObj[JV.DATA_DETAIL_DATA],
            data_fields = [];
        for (var i = 0; i < me.seg_sum_fields_idx.length; i++) {
            var data_field = data_details[me.seg_sum_fields_idx[i]];
            data_fields.push(data_field);
        }
        for (var i = 0; i < me.segments.length; i++) { //seg level
            if (me.segments[i].length > 0) {
                var rowGrandTotal = [];
                for (var di = 0; di < data_fields.length; di++) {
                    rowGrandTotal.push(0.0);
                    for (var j = 0; j < me.segments[i].length; j++) {
                        //3. start to sum
                        rowGrandTotal[di] = rowGrandTotal[di] + 1.0 * JpcFieldHelper.getValue(data_fields[di], me.segments[i][j]);
                    }
                }
                me.segSumValLst.push(rowGrandTotal);
            }

        }
    };
    JpcFlowTabResult.preSetupPages = function (rptTpl, dataOjb, defProperties) {
        var rst = 0, me = this, counterRowRec = 0, maxRowRec = 1, pageIdx = 0;
        JpcFieldHelper.findAndPutDataFieldIdx(rptTpl, rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT][JV.PROP_FLOW_FIELDS], null, me.disp_fields_idx);
        var bands = JpcBand.createNew(rptTpl, defProperties);
        var pageStatus = [true, true, false, false, false, false, false, false];
        if (rptTpl[JV.NODE_FLOW_INFO][JV.PROP_MULTI_COLUMN]) {
            me.multiCols = 1 * rptTpl[JV.NODE_FLOW_INFO][JV.PROP_MULTI_COLUMN];
        }
        function private_resetBandArea() {
            JpcBandHelper.setBandArea(bands, rptTpl, pageStatus);
            maxRowRec = JpcFlowTabHelper.getMaxRowsPerPage(bands, rptTpl);
        }
        for (var segIdx = 0; segIdx < me.segments.length; segIdx++) {
            private_resetBandArea();
            var orgMaxRowRec = maxRowRec;
            var rowSplitCnt = Math.ceil(1.0 * me.segments[segIdx].length / orgMaxRowRec);
            pageStatus[JV.STATUS_SEGMENT_END] = true;
            private_resetBandArea();
            var hasAdHocRow = !JpcFlowTabHelper.chkSegEnd(bands, rptTpl, me.segments, segIdx, (rowSplitCnt - 1) * orgMaxRowRec, maxRowRec);
            if (hasAdHocRow) rowSplitCnt++;
            if (rowSplitCnt % me.multiCols > 0) {
                rowSplitCnt++
            }
            for (var rowIdx = 0; rowIdx < rowSplitCnt; rowIdx++) {
                pageStatus[JV.STATUS_SEGMENT_END] = rowIdx == (rowSplitCnt - 1)?true:false;
                if (pageIdx > 0) pageStatus[JV.STATUS_REPORT_START] = false;
                private_resetBandArea();
                me.pageStatusLst.push(pageStatus.slice(0));
                pageIdx++;
                counterRowRec = orgMaxRowRec * rowIdx;
                private_addPageValue(me.dispValueIdxLst, me.segments[segIdx], counterRowRec, maxRowRec,me.page_seg_map, segIdx, pageIdx);
            }
            pageStatus[JV.STATUS_SEGMENT_END] = false;
            pageStatus[JV.STATUS_REPORT_START] = false;
        }
        rst = Math.ceil(1.0 * pageIdx / me.multiCols);
        return rst;
    };
    JpcFlowTabResult.outputAsSimpleJSONPage = function (rptTpl, dataObj, page, bands, controls, $CURRENT_RPT) {
        var me = this, rst = [], tabRstLst = [];
        var segIdx = JpcCommonHelper.getSegIdxByPageIdx(page, me.page_seg_map);
        //1 calculate the band position
        JpcBandHelper.setBandArea(bands, rptTpl, me.pageStatusLst[page - 1]);
        //2. start to output detail-part
        var unitFactor = JpcCommonHelper.getUnitFactor(rptTpl);
        for (var pi = 0; pi < me.multiCols; pi++) {
            var actualPage = (page - 1) * me.multiCols + pi + 1;
            //2.1 Content-Tab
            tabRstLst.push(me.outputContent(rptTpl, dataObj, actualPage, bands, unitFactor, controls, pi));
            //2.2 Column tab
            tabRstLst.push(me.outputColumn(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls, pi));
            //2.3 Sum Seg
            tabRstLst.push(me.outputSegSum(rptTpl, dataObj, actualPage, segIdx, bands, unitFactor, controls));
            //2.4 Sum Page
            //2.5 Discrete
            if (pi == 0) {
                tabRstLst.push(JpcDiscreteHelper.outputDiscreteInfo(rptTpl[JV.NODE_FLOW_INFO][JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[actualPage - 1], segIdx, 1, pi, $CURRENT_RPT));
            }
        }
        for (var i = 0; i < tabRstLst.length; i++) {
            rst = rst.concat(tabRstLst[i]);
            tabRstLst[i] = null;
        }
        return rst;
    };
    JpcFlowTabResult.outputContent = function(rptTpl, dataObj, page, bands, unitFactor, controls, multiColIdx, $CURRENT_RPT) {
        var me = this, rst = [];
        var tab = rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_CONTENT];
        var band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            var pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]] == true) {
                var tab_fields = tab[JV.PROP_FLOW_FIELDS];
                var data_details = dataObj[JV.DATA_DETAIL_DATA];
                var contentValuesIdx = me.dispValueIdxLst[page - 1];
                for (var i = 0; i < tab_fields.length; i++) {
                    var tab_field = tab_fields[i];
                    var data_field = null;
                    if (me.disp_fields_idx[i] != JV.BLANK_FIELD_INDEX) {
                        data_field = data_details[me.disp_fields_idx[i]];
                    } else {
                        data_field = JE.F(tab_field[JV.PROP_FIELD_ID], $CURRENT_RPT);
                        if (data_field) {
                            data_field = data_field[JV.PROP_AD_HOC_DATA];
                        }
                    }
                    if (!(tab_field[JV.PROP_HIDDEN])) {
                        for (var rowIdx = 0; rowIdx < contentValuesIdx.length; rowIdx++) {
                            rst.push(me.outputTabField(band, tab_field, data_field, contentValuesIdx[rowIdx], -1, contentValuesIdx.length, rowIdx, 1, 0, unitFactor, true, controls, multiColIdx));
                        }
                    }
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputColumn = function (rptTpl, dataObj, page, segIdx, bands, unitFactor, controls, multiColIdx) {
        var me = this, rst = [];
        var tab = rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_COLUMN];
        var band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            var pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]] == true) {
                if (tab[JV.PROP_TEXT]) {
                    rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXT], band, unitFactor, 1, 0, 1, 0, me.multiCols, multiColIdx));
                }
                if (tab[JV.PROP_TEXTS]) {
                    for (var j = 0; j < tab[JV.PROP_TEXTS].length; j++) {
                        rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXTS][j], band, unitFactor, 1, 0, 1, 0, me.multiCols, multiColIdx));
                    }
                }
                if (tab[JV.NODE_DISCRETE_INFO]) {
                    rst = rst.concat(JpcDiscreteHelper.outputDiscreteInfo(tab[JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, me.multiCols, multiColIdx));
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputSegSum = function (rptTpl, dataObj, page, segIdx, bands, unitFactor, controls) {
        var me = this, rst = [];
        var tab = rptTpl[JV.NODE_FLOW_INFO][JV.NODE_FLOW_SEG_SUM];
        var band = bands[tab[JV.PROP_BAND_NAME]];
        if (band) {
            var pageStatus = me.pageStatusLst[page - 1];
            if (pageStatus[band[JV.BAND_PROP_DISPLAY_TYPE]] == true) {
                var tab_fields = me.seg_sum_tab_fields;
                for (var i = 0; i < tab_fields.length; i++) {
                    var cellItem = JpcCommonOutputHelper.createCommonOutput(tab_fields[i], me.segSumValLst[segIdx][i], controls);
                    cellItem[JV.PROP_AREA] = JpcAreaHelper.outputArea(tab_fields[i][JV.PROP_AREA], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0, true, false);
                    rst.push(cellItem);
                }
                if (tab[JV.PROP_TEXT]) {
                    rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXT], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0));
                }
                if (tab[JV.PROP_TEXTS]) {
                    for (var j = 0; j < tab[JV.PROP_TEXTS].length; j++) {
                        rst.push(JpcTextHelper.outputText(tab[JV.PROP_TEXTS][j], band, unitFactor, 1, 0, 1, 0, me.multiCols, 0));
                    }
                }
                if (tab[JV.NODE_DISCRETE_INFO]) {
                    rst = rst.concat(JpcDiscreteHelper.outputDiscreteInfo(tab[JV.NODE_DISCRETE_INFO], bands, dataObj, unitFactor, me.pageStatusLst[page - 1], segIdx, me.multiCols, 0));
                }
            }
        }
        return rst;
    };
    JpcFlowTabResult.outputTabField = function (band, tab_field, data_field, valueIdx, serialIdx, rows, rowIdx, cols, colIdx, unitFactor, isRow, controls, multiColIdx) {
        var me = this, rst = null;
        rst = JpcCommonOutputHelper.createCommonOutput(tab_field, JpcFieldHelper.getValue(data_field, valueIdx), controls);
        rst[JV.PROP_AREA] = JpcAreaHelper.outputArea(tab_field[JV.PROP_AREA], band, unitFactor, rows, rowIdx, cols, colIdx, me.multiCols, multiColIdx, true, false);
        return rst;
    }

    return JpcFlowTabResult;
}

module.exports = new JpcFlowTabSrv();
