package com.braintree.customersupportbackoffice.builders;

import de.hybris.bootstrap.annotations.UnitTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.runners.MockitoJUnitRunner;

import static org.junit.Assert.assertEquals;

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

    private static final String SRC = "src";
    private static final String CHECKOUT_SRC = "checkoutSrc";
    private static final String ON_LOAD_METHOD = "onLoadMethod";
    private static final String AUTHORIZATION_ID = "authorizationId";
    private static final String EXPECTED_SCRIPT = "<script> function renderPayPalButton() {$('.paypal-preview-button-iframe').contents().find('body').append(\"<script>" +
            "function loadScript(src) {" +
            "return new Promise(function(resolve, reject) {" +
            "const script = document.createElement('script');" +
            "script.type = 'text/javascript';" +
            "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.body.appendChild(script);" +
            "}); }" +
            "loadScript('" + SRC + "').then((data) => {loadScript('" + CHECKOUT_SRC + "')}).then((data) => { " +
            "braintree.client.create({" +
            "  authorization: '" + AUTHORIZATION_ID + "'" +
            "}).then(function (clientInstance) { " +
            "  return braintree.paypalCheckout.create({" +
            "    client: clientInstance" +
            "  });" +
            "}).then(function (paypalCheckoutInstance) {" +
            " paypalCheckoutInstance.loadPayPalSDK().then(function () { " +
            " " + ON_LOAD_METHOD + " " +
            "});" + "}).catch(function (err) { console.log(err) });" +
            "});" +
            "<\\/script>\")} </script>";

    @InjectMocks
    private ScriptBuilder unit;

    @Test
    public void shouldBuildPayPalScript() {
        String result = unit.setSrc(SRC)
                .setCheckoutSrc(CHECKOUT_SRC)
                .setOnLoadMethod(ON_LOAD_METHOD)
                .setAuthorizationId(AUTHORIZATION_ID)
                .buildScript();

        assertEquals(EXPECTED_SCRIPT, result);
    }

}