package com.braintree.customersupportbackoffice.builders;

public class ScriptBuilder {
    private String src;
    private String checkoutSrc;
    private String onLoadMethod;
    private String authorizationId;

    public ScriptBuilder setSrc(String src) {
        this.src = src;
        return this;
    }

    public ScriptBuilder setOnLoadMethod(String onLoadMethod) {
        this.onLoadMethod = onLoadMethod;
        return this;
    }

    public ScriptBuilder setCheckoutSrc(String checkoutSrc) {
        this.checkoutSrc = checkoutSrc;
        return this;
    }

    public ScriptBuilder setAuthorizationId(String authorizationId) {
        this.authorizationId = authorizationId;
        return this;
    }

    public String buildScript() {
        String loadScriptFunction = "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);" +
                "}); }";

        String loadPaypalSdk = String.format("braintree.client.create({" +
                "  authorization: '%s'" +
                "}).then(function (clientInstance) { " +
                "  return braintree.paypalCheckout.create({" +
                "    client: clientInstance" +
                "  });" +
                "}).then(function (paypalCheckoutInstance) {" +
                " paypalCheckoutInstance.loadPayPalSDK().then(function () { " +
                " %s " +
                "});" + "}).catch(function (err) { console.log(err) });", authorizationId, onLoadMethod);

        return "<script> function renderPayPalButton() {$('.paypal-preview-button-iframe').contents().find('body').append(\"<script>" + loadScriptFunction +
                String.format("loadScript('%s').then((data) => {loadScript('%s')}).then((data) => { %s});", src, checkoutSrc, loadPaypalSdk) +
                "<\\/script>\")} </script>";
    }

}
