"use strict";
var __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};
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 __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    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) : adopt(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 };
    }
};
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
    result["default"] = mod;
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var React = __importStar(require("react"));
var graphql_tag_1 = __importDefault(require("graphql-tag"));
var react_apollo_1 = require("react-apollo");
var __1 = require("../../");
var context_1 = require("../../context");
var setEthAddressMutation = graphql_tag_1.default(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n  mutation($input: UserSignatureInput!) {\n    userSetEthAddress(input: $input)\n  }\n"], ["\n  mutation($input: UserSignatureInput!) {\n    userSetEthAddress(input: $input)\n  }\n"])));
var userEthAddressQuery = graphql_tag_1.default(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  query {\n    currentUser {\n      ethAddress\n    }\n  }\n"], ["\n  query {\n    currentUser {\n      ethAddress\n    }\n  }\n"])));
var AccountEthAuth = /** @class */ (function (_super) {
    __extends(AccountEthAuth, _super);
    function AccountEthAuth(props) {
        var _this = _super.call(this, props) || this;
        _this.signTransactions = function (userSetEthAddress) {
            var civil = _this.context.civil;
            if (_this.props.civil) {
                civil = _this.props.civil;
            }
            return [
                {
                    transaction: function () { return __awaiter(_this, void 0, void 0, function () {
                        var message;
                        return __generator(this, function (_a) {
                            this.setState({ isWaitingSignatureOpen: true, isSignRejectionOpen: false, errorMessage: undefined });
                            message = "I control this address @ " + new Date().toISOString();
                            return [2 /*return*/, civil.signMessage(message)];
                        });
                    }); },
                    postTransaction: function (sig) { return __awaiter(_this, void 0, void 0, function () {
                        var res, err_1;
                        return __generator(this, function (_a) {
                            switch (_a.label) {
                                case 0:
                                    _a.trys.push([0, 2, , 3]);
                                    delete sig.rawMessage; // gql endpoint doesn't want this and errors out
                                    return [4 /*yield*/, userSetEthAddress({
                                            variables: {
                                                input: sig,
                                            },
                                        })];
                                case 1:
                                    res = _a.sent();
                                    if (res && res.data && res.data.userSetEthAddress) {
                                        if (this.props.onAuthenticated) {
                                            this.props.onAuthenticated(sig.signer);
                                        }
                                        if (this._isMounted) {
                                            // A bit of an antipattern, but cancelling async/await is hard
                                            this.setState({ isWaitingSignatureOpen: false });
                                        }
                                    }
                                    else {
                                        console.error("Failed to validate and save ETH address. Response:", res);
                                        throw Error("Failed to validate and save ETH address");
                                    }
                                    return [3 /*break*/, 3];
                                case 2:
                                    err_1 = _a.sent();
                                    this.setState({
                                        isWaitingSignatureOpen: false,
                                        errorMessage: err_1,
                                    });
                                    return [3 /*break*/, 3];
                                case 3: return [2 /*return*/];
                            }
                        });
                    }); },
                    handleTransactionError: function (err) {
                        _this.setState({ isWaitingSignatureOpen: false });
                        if (err.message.indexOf("Error: MetaMask Message Signature: User denied message signature.") !== -1) {
                            _this.setState({ isSignRejectionOpen: true });
                        }
                        else {
                            console.error("Transaction failed:", err);
                            _this.setState({
                                errorMessage: "Transaction failed: " + err.message,
                            });
                        }
                    },
                },
            ];
        };
        _this.cancelTransaction = function () {
            _this.setState({
                isWaitingSignatureOpen: false,
                isSignRejectionOpen: false,
                errorMessage: undefined,
            });
        };
        _this.state = {};
        return _this;
    }
    AccountEthAuth.prototype.render = function () {
        if (this.props.buttonOnly) {
            return this.renderTransactionUI();
        }
        return (React.createElement(React.Fragment, null,
            React.createElement(__1.ManagerSectionHeading, null, "Log into Civil with your crypto wallet"),
            React.createElement("p", null, "Almost there! To set up your Civil account, you need to authenticate your account with a signature. This is similar to signing in with a password. It verifies your account with your crypto wallet."),
            React.createElement("div", null,
                React.createElement("p", null, "MetaMask will open a new window, and will require you to sign a message."),
                this.renderTransactionUI(),
                React.createElement("img", { src: __1.metaMaskSignImgUrl }))));
    };
    AccountEthAuth.prototype.componentDidMount = function () {
        this._isMounted = true;
    };
    AccountEthAuth.prototype.componentWillUnmount = function () {
        this._isMounted = false;
    };
    AccountEthAuth.prototype.renderTransactionUI = function () {
        var _this = this;
        return (React.createElement(react_apollo_1.Mutation, { mutation: setEthAddressMutation, update: function (cache, _a) {
                var userSetEthAddress = _a.data.userSetEthAddress;
                cache.writeQuery({
                    query: userEthAddressQuery,
                    data: {
                        currentUser: {
                            ethAddress: userSetEthAddress,
                            __typename: "User",
                        },
                    },
                });
            } }, function (userSetEthAddress) { return (React.createElement(React.Fragment, null,
            React.createElement(__1.TransactionButtonNoModal, { transactions: _this.signTransactions(userSetEthAddress), Button: function (props) {
                    return (React.createElement(__1.MetaMaskLogoButton, { onClick: props.onClick }, _this.props.buttonText || "Open MetaMask"));
                } }),
            _this.renderWaitingSignModal(),
            _this.renderSignRejectionModal(userSetEthAddress),
            _this.renderSaveErrorModal())); }));
    };
    AccountEthAuth.prototype.renderWaitingSignModal = function () {
        if (!this.state.isWaitingSignatureOpen) {
            return null;
        }
        return (React.createElement(__1.MetaMaskModal, { waiting: true, signing: true, cancelTransaction: this.cancelTransaction },
            React.createElement(__1.ModalHeading, null, "Please sign the text in MetaMask to authenticate")));
    };
    AccountEthAuth.prototype.renderSignRejectionModal = function (userSetEthAddress) {
        if (!this.state.isSignRejectionOpen) {
            return null;
        }
        return (React.createElement(__1.MetaMaskModal, { waiting: false, denied: true, denialText: "To authenticate that you own your wallet address, you need to sign the message in your MetaMask wallet.", cancelTransaction: this.cancelTransaction, denialRestartTransactions: this.signTransactions(userSetEthAddress) },
            React.createElement(__1.ModalHeading, null, "Failed to authenticate your wallet address")));
    };
    AccountEthAuth.prototype.renderSaveErrorModal = function () {
        if (!this.state.errorMessage) {
            return null;
        }
        return (React.createElement(__1.MetaMaskModal, { alert: true, bodyText: "Something went wrong when authenticating and saving your wallet address (" + this.state.errorMessage + "). Please try again later.", cancelTransaction: this.cancelTransaction },
            React.createElement(__1.ModalHeading, null, "Failed to save your wallet address")));
    };
    AccountEthAuth.contextType = context_1.CivilContext;
    return AccountEthAuth;
}(React.Component));
exports.AccountEthAuth = AccountEthAuth;
var templateObject_1, templateObject_2;
//# sourceMappingURL=EthAuth.js.map