package com.braintree.customersupportbackoffice.renderers;

import com.braintree.enums.BraintreeGooglePaySize;
import com.braintree.enums.BraintreeGooglePayType;
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 de.hybris.bootstrap.annotations.UnitTest;
import de.hybris.platform.core.model.BraintreeGooglePayStylesConfigurationModel;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Captor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Spy;
import org.mockito.runners.MockitoJUnitRunner;
import org.zkoss.zk.ui.Component;
import org.zkoss.zul.Html;

import java.util.List;

import static com.hybris.backoffice.workflow.designer.handler.WorkflowDesignerCloseListener.VALUE_CHANGED;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@UnitTest
@RunWith(MockitoJUnitRunner.class)
public class GooglePayPreviewButtonRendererTest {

    private static final String EXPECTED_GOOGLE_PAY_SCRIPT = "<span id='googlePay-button-container'></span><script>function loadScript(src) {    return new Promise(function (resolve, reject) {      const script = document.createElement('script');      script.src = src;      script.async = true;      script.onerror = function (err) {        reject(err, script);      };      script.onload = script.onreadystatechange = function () {        if (!this.readyState || this.readyState == 'complete') {          resolve();        }      };      document.head.appendChild(script);    });  }   function executeDelayedScript() { setTimeout(function () {    loadScript('https://pay.google.com/gp/p/js/pay.js')      .then(onGooglePayLoaded)      .catch(function (error) {        console.error('Error loading Google Pay script:', error);      });  }, 1000);  function onGooglePayLoaded() {    addGooglePayButton();  }  function addGooglePayButton() {    const paymentsClient = new google.payments.api.PaymentsClient({      environment: '',    });    const button = paymentsClient.createButton({      buttonSizeMode: 'fill',      buttonType: 'checkout',      onClick: onGooglePaymentButtonClicked,    });    button.disabled = true;    const buttonContainer = document.getElementById('googlePay-button-container');    buttonContainer.appendChild(button);  }  function onGooglePaymentButtonClicked() {}}executeDelayedScript();</script>";
    private static final String CURRENT_OBJECT_DOTLESS = "currentObject";

    @Spy
    @InjectMocks
    private GooglePayPreviewButtonRenderer unit;

    @Mock
    private Component component;
    @Mock
    private AbstractPanel abstractPanel;
    @Mock
    private BraintreeGooglePayStylesConfigurationModel stylesConfiguration;
    @Mock
    private DataType dataType;
    @Mock
    private WidgetInstanceManager widgetInstanceManager;
    @Mock
    private WidgetModel widgetModel;
    @Mock
    private Html childHtml;
    @Mock
    private Html googlePayHtml;

    @Captor
    private ArgumentCaptor<ModelObserver> modelObserverArgumentCaptor;

    @Test
    public void shouldRenderGooglePayButton() {
        doReturn(googlePayHtml).when(unit).createHtml(any());

        when(widgetInstanceManager.getModel()).thenReturn(widgetModel);
        when(stylesConfiguration.getSize()).thenReturn(BraintreeGooglePaySize.FILL);
        when(stylesConfiguration.getType()).thenReturn(BraintreeGooglePayType.CHECKOUT);

        unit.render(component, abstractPanel, stylesConfiguration, dataType, widgetInstanceManager);

        verify(unit).createHtml(EXPECTED_GOOGLE_PAY_SCRIPT);
    }

    @Test
    public void shouldNotRenderGooglePayButtonWithNullCurrentRoot() {
        doReturn(googlePayHtml).when(unit).createHtml(any());

        when(widgetInstanceManager.getModel()).thenReturn(widgetModel);
        when(widgetModel.getValue(CURRENT_OBJECT_DOTLESS, BraintreeGooglePayStylesConfigurationModel.class)).thenReturn(null);
        when(stylesConfiguration.getSize()).thenReturn(BraintreeGooglePaySize.FILL);
        when(stylesConfiguration.getType()).thenReturn(BraintreeGooglePayType.CHECKOUT);

        unit.render(component, abstractPanel, stylesConfiguration, dataType, widgetInstanceManager);

        verify(widgetModel).addObserver(eq(VALUE_CHANGED), modelObserverArgumentCaptor.capture());
        ModelObserver value = modelObserverArgumentCaptor.getValue();
        value.modelChanged();
        verify(component, never()).removeChild(childHtml);
    }

    @Test
    public void shouldAddObserver() {
        doReturn(googlePayHtml).when(unit).createHtml(any());

        when(widgetInstanceManager.getModel()).thenReturn(widgetModel);
        when(widgetModel.getValue(CURRENT_OBJECT_DOTLESS, BraintreeGooglePayStylesConfigurationModel.class)).thenReturn(stylesConfiguration);
        when(component.getChildren()).thenReturn(List.of(childHtml));
        when(stylesConfiguration.getSize()).thenReturn(BraintreeGooglePaySize.FILL);
        when(stylesConfiguration.getType()).thenReturn(BraintreeGooglePayType.CHECKOUT);

        unit.render(component, abstractPanel, stylesConfiguration, dataType, widgetInstanceManager);

        verify(widgetModel).addObserver(eq(VALUE_CHANGED), modelObserverArgumentCaptor.capture());
        ModelObserver value = modelObserverArgumentCaptor.getValue();
        value.modelChanged();
        verify(component).removeChild(childHtml);
    }

}