package com.braintree.customersupportbackoffice.renderers;

import com.braintree.configuration.service.BrainTreeConfigService;
import com.braintree.customersupportbackoffice.builders.GooglePayScriptBuilder;
import com.hybris.cockpitng.core.config.impl.jaxb.editorarea.AbstractPanel;
import com.hybris.cockpitng.core.model.ModelObserver;
import com.hybris.cockpitng.core.model.WidgetModel;
import com.hybris.cockpitng.dataaccess.facades.type.DataType;
import com.hybris.cockpitng.engine.WidgetInstanceManager;
import com.hybris.cockpitng.widgets.editorarea.renderer.impl.AbstractEditorAreaPanelRenderer;
import de.hybris.platform.core.model.BraintreeGooglePayStylesConfigurationModel;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Html;

import static com.hybris.backoffice.workflow.designer.handler.WorkflowDesignerCloseListener.VALUE_CHANGED;
import static java.util.Objects.nonNull;

public class GooglePayPreviewButtonRenderer extends AbstractEditorAreaPanelRenderer<BraintreeGooglePayStylesConfigurationModel> {
    private static final String GOOGLEPAY_SCRIPT_SRC = "https://pay.google.com/gp/p/js/pay.js";
    public static final String GOOGLEPAY_BUTTON_CONTAINER = "<span id='googlePay-button-container'></span>";

    @Override
    public void render(Component component, AbstractPanel abstractPanel,
                       BraintreeGooglePayStylesConfigurationModel braintreeGooglePayStylesConfiguration,
                       DataType dataType, WidgetInstanceManager widgetInstanceManager) {

        WidgetModel model = widgetInstanceManager.getModel();

        addGooglePayButtons(component, braintreeGooglePayStylesConfiguration);

        model.addObserver(VALUE_CHANGED, (ModelObserver) () -> {
            BraintreeGooglePayStylesConfigurationModel currentRoot =
                    model.getValue(CURRENT_OBJECT_DOTLESS, BraintreeGooglePayStylesConfigurationModel.class);
            if (nonNull(currentRoot)) {
                component.getChildren().forEach(component::removeChild);
                addGooglePayButtons(component, currentRoot);
            }
        });
    }

    private void addGooglePayButtons(Component component,
                                     BraintreeGooglePayStylesConfigurationModel model) {
        String googlePayButtons = new GooglePayScriptBuilder()
                .setSrc(GOOGLEPAY_SCRIPT_SRC)
                .setContainer(GOOGLEPAY_BUTTON_CONTAINER)
                .setButtonSizeMode(model.getSize().getCode().toLowerCase())
                .setButtonType(model.getType().getCode().toLowerCase())
                .buildScript();
        component.appendChild(createHtml(googlePayButtons));
    }

    protected Html createHtml(String content) {
        return new Html(content);
    }
}
