"use strict";
/**
 *  Copyright (c) Facebook, Inc.
 *  All rights reserved.
 *
 *  This source code is licensed under the license found in the
 *  LICENSE file in the root directory of this source tree.
 */
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    }
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = require("react");
var styled_1 = require("../../styled");
var react_redux_1 = require("react-redux");
var actions_1 = require("../../state/sessions/actions");
var reselect_1 = require("reselect");
var selectors_1 = require("../../state/sessions/selectors");
var toJS_1 = require("./util/toJS");
var json2csv_1 = require("json2csv");
/**
 * DownloadButton
 *
 * What a nice round shiny button. Shows a drop-down when there are multiple
 * queries to run.
 */
var DownloadButton = /** @class */ (function (_super) {
    __extends(DownloadButton, _super);
    function DownloadButton(props) {
        var _this = _super.call(this, props) || this;
        _this.onClick = function () {
            _this.props.responses.forEach(function (response) {
                var jsonObj = JSON.parse(response.date);
                Object.keys(jsonObj.data).forEach(function (baseKey) {
                    var key = baseKey;
                    var joinedKey = key;
                    var data = jsonObj.data[joinedKey];
                    while (!Array.isArray(data)) {
                        joinedKey = Object.keys(data)[0];
                        key += '.' + joinedKey;
                        data = data[joinedKey];
                    }
                    var flat = data.map(function (d) { return _this.flatten(d, null, null); });
                    var parser = new json2csv_1.Parser({});
                    var csv = parser.parse(flat);
                    var element = document.createElement('a');
                    element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
                    element.setAttribute('download', baseKey + ".csv");
                    element.style.display = 'none';
                    document.body.appendChild(element);
                    element.click();
                    document.body.removeChild(element);
                });
            });
        };
        // Yan Foto
        // https://stackoverflow.com/questions/19098797/fastest-way-to-flatten-un-flatten-nested-json-objects
        _this.flatten = function (obj, prefix, current) {
            prefix = prefix || [];
            current = current || {};
            if (Array.isArray(obj) && obj.length === obj.filter(function (o) { return typeof o === "string" || typeof o === "number"; }).length) {
                // join arrayed string, number values
                var joinWith = ', ';
                if (obj.length === 2) {
                    joinWith = ' - ';
                }
                obj = obj.join(joinWith);
            }
            else if (Array.isArray(obj) && obj.length === obj.filter(function (o) { return typeof o === "object"; }).length) {
                // format to be able to flatten arrays of objects
                // transform from original array to an object with indices as keys
                obj = __assign({}, obj);
            }
            if (typeof (obj) === 'object' && obj !== null) {
                Object.keys(obj).forEach(function (key) {
                    _this.flatten(obj[key], prefix.concat(key), current);
                });
            }
            else {
                current[prefix.join('.')] = obj;
            }
            return current;
        };
        _this.state = {
            optionsOpen: false,
            highlight: null,
        };
        return _this;
    }
    DownloadButton.prototype.render = function () {
        var options = null;
        // Allow click event if there is a running query or if there are not options
        // for which operation to run.
        var onClick = this.onClick;
        var pathJSX = this.props.queryRunning ? (<rect fill="#FFFFFF" x="10" y="10" width="13" height="13" rx="1"/>) : (<path d="M5.016 18h13.969v2.016h-13.969v-2.016zM18.984 9l-6.984 6.984-6.984-6.984h3.984v-6h6v6h3.984z"/>);
        return (<Wrapper>
        <Button isRunning={this.props.queryRunning} onClick={onClick} title="Download Results (csv)">
          <svg width="28" height="28" viewBox={"0,0,24,24"}>
            {pathJSX}
          </svg>
        </Button>
        {options}
      </Wrapper>);
    };
    return DownloadButton;
}(React.Component));
var mapStateToProps = reselect_1.createStructuredSelector({
    queryRunning: selectors_1.getQueryRunning,
    operations: selectors_1.getOperations,
    sessionId: selectors_1.getSelectedSessionIdFromRoot,
    responses: selectors_1.getResponses,
});
exports.default = react_redux_1.connect(mapStateToProps, { runQuery: actions_1.runQuery, stopQuery: actions_1.stopQuery })(toJS_1.toJS(DownloadButton));
var Wrapper = styled_1.styled.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n  position: absolute;\n  left: -62px;\n  z-index: 5;\n  top: 90px;\n  margin: 0 14px 0 28px;\n"], ["\n  position: absolute;\n  left: -62px;\n  z-index: 5;\n  top: 90px;\n  margin: 0 14px 0 28px;\n"])));
var Button = styled_1.styled('div')(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  width: 60px;\n  height: 60px;\n\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  border-radius: 100%;\n  transition: background-color 100ms;\n  background-color: ", ";\n  border: 6px solid ", ";\n  cursor: pointer;\n  user-select: none;\n\n  svg {\n    fill: ", ";\n  }\n\n  &:hover {\n    background-color: ", ";\n  }\n"], ["\n  width: 60px;\n  height: 60px;\n\n  display: flex;\n  align-items: center;\n  justify-content: center;\n\n  border-radius: 100%;\n  transition: background-color 100ms;\n  background-color: ",
    ";\n  border: 6px solid ", ";\n  cursor: pointer;\n  user-select: none;\n\n  svg {\n    fill: ", ";\n  }\n\n  &:hover {\n    background-color: ",
    ";\n  }\n"])), function (p) {
    return p.isRunning
        ? p.theme.editorColours.executeButtonSubscription
        : p.theme.editorColours.executeButton;
}, function (p) { return p.theme.editorColours.executeButtonBorder; }, function (p) { return (p.theme.mode === 'light' ? 'white' : 'inherit'); }, function (p) {
    return p.isRunning
        ? p.theme.editorColours.executeButtonSubscriptionHover
        : p.theme.editorColours.executeButtonHover;
});
var templateObject_1, templateObject_2;
//# sourceMappingURL=DownloadButton.jsx.map