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 __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);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { withStyles } from '@signatu/styles';
import { Consent, CONSENT_TEXTS, ConsentActionType } from '@signatu/consent';
import PropTypes from 'prop-types';
import React from 'react';
import { CONSENT_BASE_PROPTYPES } from '../lib/consentBase';
import { defaultButton } from '../styles/button';
var styles = function (theme) { return ({
    root: {},
    button: defaultButton(theme),
    checkboxContainer: {
        display: "flex",
        alignItems: "center"
    },
    checkbox: {
        marginRight: theme.spacing.unit * 2
    },
    checkboxLabel: {},
    textContainer: {
        color: theme.palette.text.main,
        userSelect: "none",
        '-moz-user-select': "none"
    },
    buttonContainer: {
        marginTop: theme.spacing.unit * 2
    },
    acceptButton: {
        border: "1px solid " + theme.palette.balanced.main,
        color: theme.palette.balanced.main,
        background: theme.palette.backgroundColor
    },
    acceptButtonActive: {
        color: theme.palette.balanced.contrastText,
        background: theme.palette.balanced.main
    },
    denyButton: {
        color: theme.palette.attention.main,
        border: "1px solid " + theme.palette.attention.main,
        background: theme.palette.backgroundColor
    },
    denyButtonActive: {
        color: theme.palette.attention.contrastText,
        background: theme.palette.attention.main
    }
}); };
var ConsentAction = /** @class */ (function (_super) {
    __extends(ConsentAction, _super);
    function ConsentAction() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.state = { checked: false, language: 'en' };
        /**
         *
         * See https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
         *
         * We track this because our loadConsent may complete after the component has been unloaded.
         */
        _this.componentIsMounted = false;
        _this.updateState = function (consent, userAction) {
            if (userAction === void 0) { userAction = true; }
            _this.setState({ consent: consent, checked: _this.checkedState(consent) });
            if (userAction && consent && _this.props.onAction) {
                _this.props.onAction(consent);
            }
        };
        _this.checkedState = function (event) {
            if (!event) {
                // No event found - if we have a optOut model => checked by default
                if (_this.props.optOut) {
                    return !!_this.props.optOut;
                }
            }
            return event ? !!event.action : false;
        };
        /* Has the user actively accepted or denied? That requires a consent event */
        _this.activeAccept = function () { return _this.state.consent ? _this.state.consent.action === true : false; };
        _this.activeDeny = function () { return _this.state.consent ? _this.state.consent.action === false : false; };
        _this.loadConsent = function (props) { return __awaiter(_this, void 0, void 0, function () {
            var consent, consents, e_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!(props.config &&
                            props.config.accessToken &&
                            props.config.apiKey &&
                            props.subject &&
                            props.issuer &&
                            props.target)) {
                            return [2 /*return*/, console.warn("ConsentAction: cannot mount without config, subject, issuer and target", props)];
                        }
                        if (props.language) {
                            this.setState({ language: props.language });
                        }
                        consent = undefined;
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, 4, 5]);
                        this.consentService = new Consent(props.config, props.subject, props.issuer, props.target, document && document.location && document.location.href, props.delegate);
                        return [4 /*yield*/, this.consentService.get(props.scope)];
                    case 2:
                        consents = _a.sent();
                        consent = consents ? consents[0] : undefined;
                        return [3 /*break*/, 5];
                    case 3:
                        e_1 = _a.sent();
                        console.warn("ConsentAction: Unable to load consent: ", e_1);
                        return [3 /*break*/, 5];
                    case 4:
                        /** This may complete after we've unmounted */
                        if (!this.componentIsMounted) {
                            return [2 /*return*/];
                        }
                        if (props.onLoaded) {
                            props.onLoaded(consent);
                        }
                        this.updateState(consent, false);
                        return [7 /*endfinally*/];
                    case 5: return [2 /*return*/];
                }
            });
        }); };
        _this.onChange = function (event) { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                if (!(event && event.target && this.consentService)) {
                    return [2 /*return*/];
                }
                this.setAction(event.target.checked);
                return [2 /*return*/];
            });
        }); };
        _this.setAction = function (action) { return __awaiter(_this, void 0, void 0, function () {
            var previousCheckedState, consent, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.consentService) {
                            return [2 /*return*/, console.warn("setAction: consentService is not initialized")];
                        }
                        previousCheckedState = this.state.checked;
                        /** First set the action immediately to update the UI */
                        this.setState({ checked: action });
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.consentService.set(action, this.props.scope)
                            /** Update the state with the status from the consent event. */
                        ];
                    case 2:
                        consent = _a.sent();
                        /** Update the state with the status from the consent event. */
                        this.updateState(consent);
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        /** E.g., API down, invalid access token. Set the previous state and rethrow the error */
                        this.setState({ checked: previousCheckedState });
                        throw error_1;
                    case 4: return [2 /*return*/];
                }
            });
        }); };
        return _this;
    }
    ConsentAction.prototype.componentWillUnmount = function () {
        this.componentIsMounted = false;
    };
    ConsentAction.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                this.componentIsMounted = true;
                this.loadConsent(this.props);
                return [2 /*return*/];
            });
        });
    };
    ConsentAction.prototype.componentDidUpdate = function (prevProps) {
        var _a = this.props, config = _a.config, subject = _a.subject, issuer = _a.issuer, target = _a.target;
        /** Support changing config */
        if (prevProps.config !== config ||
            prevProps.issuer !== issuer ||
            prevProps.target !== target ||
            prevProps.subject !== subject) {
            this.loadConsent(this.props);
        }
    };
    ConsentAction.prototype.componentWillReceiveProps = function (props) {
        var language = props.language, subject = props.subject, issuer = props.issuer, target = props.target, scope = props.scope;
        if (language && language !== this.state.language) {
            this.setState({ language: language });
        }
        /** If subject, issuer, target or scope changes we need to reload consent */
        if (subject !== this.props.subject ||
            issuer !== this.props.issuer ||
            target !== this.props.target ||
            scope !== this.props.scope) {
            this.loadConsent(props);
        }
    };
    ConsentAction.prototype.render = function () {
        var _this = this;
        // CSS classes for the buttons
        var classes = this.props.classes;
        var _a = this.state, checked = _a.checked, consent = _a.consent;
        var acceptText = this.props.acceptText || CONSENT_TEXTS[this.state.language].BUTTON_ACCEPT;
        var refuseText = this.props.refuseText || CONSENT_TEXTS[this.state.language].BUTTON_REFUSE;
        return React.createElement("div", { className: classes.root, "data-type": "ConsentAction" },
            this.props.type === ConsentActionType.CHECKBOX && React.createElement("div", { className: classes.checkboxContainer, "data-type": "ConsentCheckbox" },
                React.createElement("input", { className: classes.checkbox, type: "checkbox", checked: checked, onChange: this.onChange, id: this.props.id }),
                React.createElement("label", { className: classes.checkboxLabel, htmlFor: this.props.id }),
                React.createElement("label", { className: classes.textContainer, htmlFor: this.props.id }, this.props.children)),
            this.props.type === ConsentActionType.BUTTONS && React.createElement("div", { "data-type": "ConsentButtons" },
                React.createElement("div", { className: classes.textContainer }, this.props.children),
                React.createElement("div", { className: classes.buttonContainer },
                    React.createElement("button", { className: classes.button + " " + classes.acceptButton + " " + (consent && checked ? classes.acceptButtonActive : ""), onClick: function () { return _this.setAction(true); } }, acceptText),
                    React.createElement("button", { className: classes.button + " " + classes.denyButton + " " + (consent && !checked ? classes.denyButtonActive : ""), onClick: function () { return _this.setAction(false); } }, refuseText))));
    };
    /** PropTypes for non-Typescript environments */
    ConsentAction.propTypes = __assign({}, CONSENT_BASE_PROPTYPES, { 
        /** See https://github.com/DefinitelyTyped/DefinitelyTyped/pull/27973 */
        id: PropTypes.string, type: PropTypes.string, acceptText: PropTypes.string, refuseText: PropTypes.string, classes: PropTypes.object });
    return ConsentAction;
}(React.Component));
var styled = withStyles(styles)(ConsentAction);
export { styled as ConsentAction };
//# sourceMappingURL=consentAction.js.map