import * as React from 'react';
import FramePayError from '../../framepay-error';
import BaseElement from './base-element';
import type {
    GooglePayProps,
    GooglePayState,
} from '../../../../types/elements';

export default class GooglePayElement extends BaseElement<
    GooglePayProps,
    GooglePayState
> {
    setupElement() {
        const { Framepay } = this.props;

        const makeElement = () => {
            // elementNode already checked in BaseElement.handleSetupElement
            // just ts checks fix
            if (!this.elementNode) {
                throw FramePayError({
                    code: FramePayError.codes.elementMountError,
                    details: `GooglePayElement invalid elementNode`,
                });
            }

            try {
                return Framepay.googlePay.mount(this.elementNode);
            } catch (e) {
                throw FramePayError({
                    code: FramePayError.codes.elementMountError,
                    details: `GooglePayElement error in remote api call`,
                    trace: e,
                });
            }
        };

        const element = makeElement();
        this.setState({ element });
    }
}
