"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 qs = __importStar(require("querystring"));
var react_apollo_1 = require("react-apollo");
var graphql_tag_1 = __importDefault(require("graphql-tag"));
var styled_components_1 = __importDefault(require("styled-components"));
var CivilContext_1 = require("../context/CivilContext");
var WithNewsroomChannelHOC_1 = require("../WithNewsroomChannelHOC");
var DashboardStyledComponents_1 = require("./DashboardStyledComponents");
var icons_1 = require("../icons");
var styleConstants_1 = require("../styleConstants");
var Button_1 = require("../Button");
var stripe_logo_blue_png_1 = __importDefault(require("../images/stripe-logo-blue.png"));
var stripe_connect_blue_on_light_png_1 = __importDefault(require("../images/stripe-connect-blue-on-light.png"));
var stripe_connect_blue_on_dark_png_1 = __importDefault(require("../images/stripe-connect-blue-on-dark.png"));
exports.StripeContainer = styled_components_1.default.div(templateObject_1 || (templateObject_1 = __makeTemplateObject(["\n  border: 1px solid ", ";\n  padding: 20px 16px 24px;\n"], ["\n  border: 1px solid ", ";\n  padding: 20px 16px 24px;\n"])), styleConstants_1.colors.accent.CIVIL_GRAY_4);
var StripeLogo = styled_components_1.default.img(templateObject_2 || (templateObject_2 = __makeTemplateObject(["\n  display: block;\n  height: 24px;\n  margin-bottom: 10px;\n  width: auto;\n"], ["\n  display: block;\n  height: 24px;\n  margin-bottom: 10px;\n  width: auto;\n"])));
var StripeConnectButtonLink = styled_components_1.default.a(templateObject_3 || (templateObject_3 = __makeTemplateObject(["\n  background-size: contain;\n  display: inline-block;\n  height: 33px;\n  width: 190px;\n\n  background-image: url(\"", "\");\n  &:hover {\n    background-image: url(\"", "\");\n  }\n  // Preload image to prevent flash on hover:\n  &:after {\n    content: url(\"", "\");\n    position: absolute;\n    left: -50000px;\n  }\n"], ["\n  background-size: contain;\n  display: inline-block;\n  height: 33px;\n  width: 190px;\n\n  background-image: url(\"", "\");\n  &:hover {\n    background-image: url(\"", "\");\n  }\n  // Preload image to prevent flash on hover:\n  &:after {\n    content: url(\"", "\");\n    position: absolute;\n    left: -50000px;\n  }\n"])), stripe_connect_blue_on_light_png_1.default, stripe_connect_blue_on_dark_png_1.default, stripe_connect_blue_on_dark_png_1.default);
exports.CHANNEL_CONNECT_STRIPE_MUTATION = graphql_tag_1.default(templateObject_4 || (templateObject_4 = __makeTemplateObject(["\n  mutation($input: ChannelsConnectStripeInput!) {\n    channelsConnectStripe(input: $input) {\n      id\n    }\n  }\n"], ["\n  mutation($input: ChannelsConnectStripeInput!) {\n    channelsConnectStripe(input: $input) {\n      id\n    }\n  }\n"])));
var DashboardNewsroomStripeConnectComponent = /** @class */ (function (_super) {
    __extends(DashboardNewsroomStripeConnectComponent, _super);
    function DashboardNewsroomStripeConnectComponent(props) {
        var _this = _super.call(this, props) || this;
        _this.state = {};
        _this.qsParams = qs.parse(document.location.search.substr(1));
        return _this;
    }
    DashboardNewsroomStripeConnectComponent.prototype.componentDidMount = function () {
        return __awaiter(this, void 0, void 0, function () {
            var err_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.qsParams.code) return [3 /*break*/, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        this.setState({ connectingStripe: true });
                        return [4 /*yield*/, this.props.client.mutate({
                                mutation: exports.CHANNEL_CONNECT_STRIPE_MUTATION,
                                variables: { input: { channelID: this.props.channelData.id, oauthCode: this.qsParams.code } },
                                refetchQueries: [
                                    {
                                        query: WithNewsroomChannelHOC_1.CHANNEL_BY_NEWSROOM_QUERY,
                                        variables: {
                                            contractAddress: this.props.newsroomAddress,
                                        },
                                    },
                                ],
                            })];
                    case 2:
                        _a.sent();
                        this.setState({ connectingStripe: false });
                        return [3 /*break*/, 4];
                    case 3:
                        err_1 = _a.sent();
                        console.error("error running channelsConnectStripe mutation:", err_1);
                        this.setState({ connectStripeError: err_1 });
                        return [3 /*break*/, 4];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    DashboardNewsroomStripeConnectComponent.prototype.render = function () {
        return (React.createElement(React.Fragment, null,
            React.createElement(DashboardStyledComponents_1.StyledDashboardNewsroomHdr, null, "Credit Card Payments Setup"),
            React.createElement("p", null,
                "Connect a Stripe account to accept credit card payments for your Boosts. You can link your existing Stripe account or start a new one.",
                " ",
                React.createElement("a", { href: "#@TODO/tobek", target: "_blank" }, "Learn more")),
            React.createElement(exports.StripeContainer, null,
                React.createElement(StripeLogo, { src: stripe_logo_blue_png_1.default }),
                this.renderBody())));
    };
    DashboardNewsroomStripeConnectComponent.prototype.renderBody = function () {
        if (!this.props.channelData.currentUserIsAdmin) {
            return (React.createElement(React.Fragment, null,
                React.createElement(icons_1.ErrorIcon, { width: 16, height: 16 }),
                " You are not an admin for this Newsroom, so you cannot edit its Stripe settings. Please contact an admin to be added."));
        }
        else if (!this.state.connectingStripe && this.props.channelData.isStripeConnected) {
            var justConnected = this.qsParams.code;
            return (React.createElement(React.Fragment, null,
                React.createElement("p", null,
                    justConnected ? "Connection successful! You are now" : "You are currently",
                    " accepting credit cards through your connected Stripe account."),
                React.createElement("p", null,
                    React.createElement(Button_1.InvertedButton, { size: Button_1.buttonSizes.SMALL, href: "https://dashboard.stripe.com", target: "_blank" },
                        "Go to Your Stripe Dashboard",
                        React.createElement(icons_1.NorthEastArrow, { color: styleConstants_1.colors.accent.CIVIL_BLUE }))),
                !justConnected && this.renderStripeConnectButton("Connect a different Stripe account")));
        }
        else if (this.state.connectStripeError) {
            return (React.createElement(React.Fragment, null,
                React.createElement("p", null,
                    React.createElement(icons_1.ErrorIcon, { width: 16, height: 16 }),
                    " Sorry, there was an error connecting your Newsroom to your Stripe account:",
                    " ",
                    React.createElement("code", null, JSON.stringify(this.state.connectStripeError.message || this.state.connectStripeError)),
                    ". Please try again."),
                this.renderStripeConnectButton()));
        }
        else if (this.state.connectingStripe || this.qsParams.code) {
            return React.createElement(DashboardStyledComponents_1.StyledDashboardLoadingMessage, null, "Connecting your Stripe account");
        }
        else if (this.qsParams.error) {
            return (React.createElement(React.Fragment, null,
                React.createElement("p", null,
                    React.createElement(icons_1.ErrorIcon, { width: 16, height: 16 }),
                    " Error connecting your Stripe account: ",
                    this.qsParams.error,
                    ":",
                    " ",
                    this.qsParams.error_description,
                    ". Please try again."),
                this.renderStripeConnectButton()));
        }
        else {
            return (React.createElement(React.Fragment, null,
                React.createElement("p", null, "Allows you to accept credit card payments for your Boosts. Stripe fees will apply. The Boost amounts sent by supporters will go directly into your connected Stripe account. Civil will not keep or hold any of your proceeds."),
                this.renderStripeConnectButton()));
        }
    };
    DashboardNewsroomStripeConnectComponent.prototype.renderStripeConnectButton = function (linkText) {
        var redirectUrl = document.location.origin + "/dashboard/newsrooms";
        var oauthUrl = "https://connect.stripe.com/oauth/authorize?response_type=code&client_id=" + this.context.config.STRIPE_CLIENT_ID + "&scope=read_write&redirect_uri=" + encodeURIComponent(redirectUrl);
        return React.createElement("p", null, linkText ? React.createElement("a", { href: oauthUrl }, linkText) : React.createElement(StripeConnectButtonLink, { href: oauthUrl }));
    };
    DashboardNewsroomStripeConnectComponent.contextType = CivilContext_1.CivilContext;
    return DashboardNewsroomStripeConnectComponent;
}(React.Component));
exports.DashboardNewsroomStripeConnectComponent = DashboardNewsroomStripeConnectComponent;
exports.DashboardNewsroomStripeConnect = WithNewsroomChannelHOC_1.withNewsroomChannel(react_apollo_1.withApollo(DashboardNewsroomStripeConnectComponent));
var templateObject_1, templateObject_2, templateObject_3, templateObject_4;
//# sourceMappingURL=DashboardNewsroomStripeConnect.js.map