const helper = require("./helper.js");

function esia() {
  if (document.location.search == '?esia=true') {
    const hostName = helper.getHostname();

    window.webSDK.on('init', function() {
     
      if (!window.webSDK?.data?.user?.authenticated) 
        return;
          
      const user = window.webSDK?.data?.user;
        
      $.ajax({
        method: "POST",
        crossDomain: false,
        url: "/api/authenticated",
        contentType: "application/x-www-form-urlencoded",
        dataType: "json",
        data: {
          user: user,
          uid: user.id
        },
        xhrFields: {
          withCredentials: true
        },
        success(response) {
          if (response.data.success == true) {
            const parser = document.createElement('a');
            parser.href = response.data.redirect;

            window.location.replace(document.location.origin + parser.pathname + parser.search);
          }        
        }
      });
    });
  }
};

function loadSDK(controller) {
  return new Promise(function(resolve, reject) {
    var script = document.getElementById('sdk-infoclinica');

    if (script == null) {
      var script = document.createElement('script');

     if (/sovamed\.ru/m.test(location.hostname)) {
          script.src = 'https://widget.sovamed.ru/assets/javascripts/sdk/sdk.build.min.js';
      } else {
          script.src = 'https://widget.wmtmed.ru/assets/javascripts/sdk/sdk.build.min.js';
      }

      script.id = "sdk-infoclinica";
      document.head.appendChild(script);
      
      script.addEventListener('load', function() {
        console.log(controller + ' - load');
        window.webSDK = new WrSDK();
        esia();
        resolve(window.webSDK);
      });
    } else {
      script.addEventListener('load', function() {
        console.log(controller + ' - onload');
        esia();
        resolve(window.webSDK);
      });
    }
  });
}

function btnLoader(btn, disabled = true) {
  if (disabled) {
    btn.dataset.name = btn.innerHTML;
    btn.style.paddingRight = '5px';
    btn.disabled = disabled;
    btn.innerHTML = 'Загрузка&nbsp;<img width="20" src="'+ helper.getHostname() +'/images/eclipse.gif">';
  } else {
    btn.style.paddingRight = null;
    btn.disabled = disabled;
    btn.innerHTML = btn.dataset.name;
  }
}

// Exporting loadSDK function
module.exports = {
  loadSDK: loadSDK,
  btnLoader: btnLoader
};
