//React
import * as React from 'react';
import * as ReactDOM from 'react-dom';
//Application
import * as wjcCore from 'wijmo/wijmo';
import * as wjcInput from 'wijmo/wijmo.input';
import * as wjInput from 'wijmo/wijmo.react.input';
import * as wjOlap from 'wijmo/wijmo.react.olap';
import * as wjcOlap from 'wijmo/wijmo.olap';
import * as wjcGrid from 'wijmo/wijmo.grid';
import * as wjcGridXlsx from 'wijmo/wijmo.grid.xlsx';
import * as wjcXlsx from 'wijmo/wijmo.xlsx';
import { Tabs, TabPane } from './Tabs';
import { DataSvc } from '../services/DataSvc';

export class Export extends React.Component<any, any> {

    constructor(props) {
        super(props);

    }
    // export pivot table and raw data to Excel
    export() {
        var ng = this.props.engine,
            pivotGrid = wjcCore.Control.getControl(document.getElementById('thePivotGrid')) as wjcGrid.FlexGrid,
            rawGrid = wjcCore.Control.getControl(document.getElementById('theRawGrid')) as wjcGrid.FlexGrid;

        // create book with current view
        var book = wjcGridXlsx.FlexGridXlsxConverter.save(pivotGrid, {
            includeColumnHeaders: true,
            includeRowHeaders: true
        });
        book.sheets[0].name = 'Main View';
        this.addTitleCell(book.sheets[0], this.getViewTitle(ng));

        // add sheet with transposed view
        // add sheet with transposed view
        if (!wjcCore.isString(ng.itemsSource)) {
            this.transposeView(ng);
            var transposed = wjcGridXlsx.FlexGridXlsxConverter.save(pivotGrid, {
                includeColumnHeaders: true,
                includeRowHeaders: true
            });
            transposed.sheets[0].name = 'Transposed View';
            this.addTitleCell(transposed.sheets[0], this.getViewTitle(ng));
            book.sheets.push(transposed.sheets[0]);
            this.transposeView(ng);

            // add sheet with raw data (unless there's too much data)
            if (ng.itemsSource.items.length < 20000) {
                var raw = wjcGridXlsx.FlexGridXlsxConverter.save(rawGrid, {
                    includeColumnHeaders: true,
                    includeRowHeaders: false
                });
                raw.sheets[0].name = 'Raw Data';
                book.sheets.push(raw.sheets[0]);
            }
        }

        // save the book
        book.save('wijmo.olap.xlsx');
    }


    // save/load/transpose/export views
    private transposeView(ng: wjcOlap.PivotEngine) {
        ng.deferUpdate(() => {

            // save row/col fields
            var rows = [],
                cols = [];
            for (var r = 0; r < ng.rowFields.length; r++) {
                rows.push(ng.rowFields[r].header);
            }
            for (var c = 0; c < ng.columnFields.length; c++) {
                cols.push(ng.columnFields[c].header);
            }

            // clear row/col fields
            ng.rowFields.clear();
            ng.columnFields.clear();

            // restore row/col fields in transposed order
            for (var r = 0; r < rows.length; r++) {
                ng.columnFields.push(rows[r]);
            }
            for (var c = 0; c < cols.length; c++) {
                ng.rowFields.push(cols[c]);
            }
        });
    }

    // build a title for the current view
    private getViewTitle(ng: wjcOlap.PivotEngine): string {
        var title = '';
        for (var i = 0; i < ng.valueFields.length; i++) {
            if (i > 0) title += ', ';
            title += ng.valueFields[i].header;
        }
        title += ' by ';
        if (ng.rowFields.length) {
            for (var i = 0; i < ng.rowFields.length; i++) {
                if (i > 0) title += ', ';
                title += ng.rowFields[i].header;
            }
        }
        if (ng.rowFields.length && ng.columnFields.length) {
            title += ' and by ';
        }
        if (ng.columnFields.length) {
            for (var i = 0; i < ng.columnFields.length; i++) {
                if (i > 0) title += ', ';
                title += ng.columnFields[i].header;
            }
        }
        return title;
    }

    // adds a title cell into an xlxs sheet
    private addTitleCell(sheet: wjcXlsx.WorkSheet, title: string) {

        // create cell
        var cell = new wjcXlsx.WorkbookCell();
        cell.value = title;
        cell.style = new wjcXlsx.WorkbookStyle();
        cell.style.font = new wjcXlsx.WorkbookFont();
        cell.style.font.bold = true;

        // create row to hold the cell
        var row = new wjcXlsx.WorkbookRow();
        row.cells[0] = cell;

        // and add the new row to the sheet
        sheet.rows.splice(0, 0, row);
    }

    render () {
        return <div>
            <h4>
                Export the results to Excel</h4>
            <p>
                The <b>PivotGrid</b> control extends the <b>FlexGrid</b>, so you can export it to any of
                the formats supported by the extension modules provided with the <b>FlexGrid</b>. The
                list of supported formats includes XLSLX, CSV, and PDF.</p>
            <p>
                For example, the button below creates an Excel file with three sheets: the current view,
                a transposed version of the current view, and the raw data:</p>

            <button
                className="mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect"
                onClick={this.export.bind(this)} >
                Export to XLSX
            </button>

            <div className="source-card mdl-card mdl-shadow--2dp">
                <Tabs selected={3}>
                    <TabPane label="JSX">
                        <code className="pane-content">
                            {'   <button\n'}
                            {'       className="mdl-button mdl-js-button mdl-button--raised mdl-button--colored mdl-js-ripple-effect"\\n'}
                            {'       onClick={this.export.bind(this)} >\n'}
                            {'       Export to XLSX\n'}
                            {'   </button>\n'}
                        </code>
                    </TabPane>
                    <TabPane label="TS">
                        <code className="pane-content">
                            {'  export() {\n'}
                            {'      var ng = this.props.engine,\n'}
                            {'          pivotGrid = wjcCore.Control.getControl(document.getElementById(\'thePivotGrid\')) as wjcGrid.FlexGrid,\n'}
                            {'          rawGrid = wjcCore.Control.getControl(document.getElementById(\'theRawGrid\')) as wjcGrid.FlexGrid;\n'}
                            {'\n'}
                            {'      // create book with current viewn'}
                            {'      var book = wjcGridXlsx.FlexGridXlsxConverter.save(pivotGrid, {\n'}
                            {'          includeColumnHeaders: true,\n'}
                            {'          includeRowHeaders: truen'}
                            {'      });\n'}
                            {'      book.sheets[0].name = \'Main View\';\n'}
                            {'      this.addTitleCell(book.sheets[0], this.getViewTitle(ng));\n'}
                            {'\n'}
                            {'      // add sheet with transposed viewn\n'}
                            {'      if (!wjcCore.isString(ng.itemsSource)) {\n'}
                            {'          this.transposeView(ng);\n'}
                            {'          var transposed = wjcGridXlsx.FlexGridXlsxConverter.save(pivotGrid, {\n'}
                            {'              includeColumnHeaders: true,\n'}
                            {'              includeRowHeaders: truen'}
                            {'          });\n'}
                            {'          transposed.sheets[0].name = \'Transposed View\';\n'}
                            {'          this.addTitleCell(transposed.sheets[0], this.getViewTitle(ng));\n'}
                            {'          book.sheets.push(transposed.sheets[0]);\n'}
                            {'          this.transposeView(ng);\n'}
                            {'\n'}
                            {'          // add sheet with raw data (unless there\'s too much data)\n'}
                            {'          if (ng.itemsSource.items.length < 20000) {\n'}
                            {'              var raw = wjcGridXlsx.FlexGridXlsxConverter.save(rawGrid, {\n'}
                            {'                  includeColumnHeaders: true,\n'}
                            {'                  includeRowHeaders: falsen'}
                            {'              });\n'}
                            {'              raw.sheets[0].name = \'Raw Data\';\n'}
                            {'              book.sheets.push(raw.sheets[0]);\n'}
                            {'          }\n'}
                            {'      }\n'}
                            {'\n'}
                            {'      // save the bookn'}
                            {'      book.save(\'wijmo.olap.xlsx\');\n'}
                            {'  }\n'}
                                </code>
                    </TabPane>
                    <TabPane label="X">
                    </TabPane>
                </Tabs>

            </div>
        </div>;
    }
}
